If Statement Within an Array Declaration ...Is That Possible

If statement inside array?

You can use ternary conditions, which is a shortcut for an if statement. Here is an example of how ternary conditions works :

A regular if would be written like this :

if( "mycondition" == 1 )
{
$boolean = true;
}
else {
$boolean = false;
}

The equivalent of this statement with ternary condition would be written like below :

$boolean = ( "mycondition" == 1 ) ? true : false;

You might want to use this shortcut to instanciate your array like following :

$sales_payload = [
// ...
'custom_fields' => ( strpos($_POST['billing_myfield13'], 'ja') !== false ) ? [['actief_duitsland' => 1]] : [['actief_duitsland' => '???']],
// ...
];

Warning

You should also define a else value for this statement.

How can I use an if statement inside an array?

'data' => $target == 'new' ? new \DateTime() : ''

java-Declaring Array Based on If Statement

An alternative solution would be:

double data[][] = new double[winner ? 16 : 14][5];

The x ? a : b thing is called a "ternary operator". It evaluates to a if x is true, otherwise b.

JavaScript: If statement on Array declaration

What you need is called the ternary or conditional operator:

$('#domingo').checked() ? $('#domingo').val() : 0

However, it is not a good idea to query the DOM twice for the same element. Save the resulting jQuery object into a variable beforehand and reuse it:

var $domi = $('#domingo');
dayOfWeek = [$domi.checked() ? $domi.val() : 0];

I don't know what .checked() is, maybe you meant .is(':checked').

Some fiddle demo to play with

PHP if then else inside an array

This is similar to mzedeler answer but it work

$testflag = 'test';

$test = array(

'auxiliaryFields' => array(
array(
'key' => 'extra1',
'label' => 'TEST',
'value' => 'TEST',
'textAlignment' => 'PKTextAlignmentLeft'
)
));

var_dump($test);
if ($testflag != ''){
$test['auxiliaryFields'][]=array(
'key' => 'extra2',
'label' => 'TEST2',
'value' => 'TEST2',
'textAlignment' => 'PKTextAlignmentLeft'
);
}

var_dump($test);

I've changed $test['auxiliaryFields'][0][] with $test['auxiliaryFields'][] and fixed a sintax error (missing ;)

Using an If-else within an array

Yes, this is possible using a certain shorthand:

<?php

$LibraryStatus = $ControlStatus = true;

$arrLayout = array(
"section1" => array(
($LibraryStatus ? array("wLibrary" => array("title" => "XMBC Library",
"display" => "")) : false),
($ControlStatus ? array("wControl" => array("title" => "Control",
"display" => "")) : false)));

print_r($arrLayout);

?>

It works like this:

if($a == $b){ echo 'a'; }else{ echo 'b'; }

is equal to

echo $a == $b ? 'a' : 'b';

If you use this shorthand it will always return the output, so you can put it between brackets and put it inbetween the array.

http://codepad.org/cxp0M0oL

But for this exact situation there are other solutions as well.



Related Topics



Leave a reply



Submit