How can I add a condition inside a php array?
Unfortunately that's not possible at all.
If having the item but with a NULL value is ok, use this:
$anArray = array(
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => "the last item"
);
Otherwise you have to do it like that:
$anArray = array(
"theFirstItem" => "a first item",
"theLastItem" => "the last item"
);
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
If the order matters, it'll be even uglier:
$anArray = array("theFirstItem" => "a first item");
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
You could make this a little bit more readable though:
$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
How to add if condition in php multidimensional array
You can't put PHP control structures in the middle of defining an array like that. First create the array with the default values, then put the if-statement after and push new elements to the array, if needed.
Something like this:
$data = array(
"personalizations" => array(
array(
"to" => array(
array("email" => $userEmail, "name" => $userName)
),
)
),
"from" => array("email" => $senderEmail, "name" => $senderName),
"subject" => $subject,
"content" => array(array("type" => "text/html", "value" => $body))
);
// Now add the condition
if(strpos($check, "SUCCESS") === false){
$data['personalizations'][0]["CC"] = array(
array("email" => $adminEmail,"name" => $adminEmail)
)
}
Multiple Condition inside php array
$arr = [[472 => ['EL' => 52.9, 'MT' => 57.375, 'MO' => 56.6, 'SC' => 26, 'ET' => 50.775]],
[505 => ['EL' => 53.425, 'MT' => 25, 'MO' => 62.8, 'SC' => 23, 'ET' => 26]]];
function pr($arr)
{
echo "<pre>";
print_r($arr);
echo "</pre>";
}
$total = array_reduce($arr, function ($arr, $key) {
$id = key($key);
$temp = $consumed = $key[$id];
$sc = array_keys($consumed);
$condition = false;
if (array_search('SC', $sc) && ($consumed['SC']) >= 23) {
$condition = true;
}
unset($temp['SC']);
$condition = ($condition && min($temp) >= 26 ? true : false);
$arr[$id] = [
"totalc" => array_sum($consumed),
"condition" => $condition,
];
return $arr;
});
pr($total);die;
if min SC is 23 and min of all other is 26 then condition is true.
Explanation:
472 => SC = 26(>=23) and all other values are >= 26 so condition = true
505 => SC = 23(>=23) and now I will check other values. Now MT = 25 so condition = false
Lets take some sample demo examples,
$arr = [[472 => ['EL' => 52.9, 'MT' => 57.375, 'MO' => 56.6, 'SC' => 22, 'ET' => 50.775]],
[505 => ['EL' => 53.425, 'MT' => 26, 'MO' => 62.8, 'SC' => 23, 'ET' => 26]]];
472 => SC < 23 so condition = false
regardless of other value.
505 => SC >= 23 so condition = true
at first, now we will check for all other values. As we saw all other are greater than 26, so condition =true
.
Working demo
Conditionally add to an array
You are overwriting $connected
with an empty array each time your foreach
loop iterates. Move the assignment of $connected
to before your foreach
loop.
$key1 = '0';
$connected = array();
foreach ($dataNewAndUnlock1 as $key => $val) {
...
Also, to append to an array, you don't need to maintain your own index, you can just use this syntax:
$connected[] = $val;
PHP add element to array only when condition is true
Let's introduce a temporary array:
$tempArray=Array(
'NmbItem' => $item['name'],
'QtyItem' => (int)$item['quantity'],
'PrcItem' => $item['price']
);
if ($cond){
$tempArray['IndExe'] = 1;
}
$ab['Detalle'][] = $tempArray;
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.
display the array which meets only this condition in php
We would loop over each subarray and count how many norm_value
has 0.0
. If the count matches the size
or size-1
, then we unset that index.
$epsilon = 0.00001;
foreach($arr as $index => $subarray){
$count = 0;
foreach($subarray as $norm_data){
if(abs($norm_data['norm_value'] - 0.0) < $epsilon) $count++;
}
if($count === count($subarray) || $count == count($subarray)-1){
unset($arr[$index]);
}
}
print_r($arr);
Demo: https://3v4l.org/futQ8
Conditionally add associative element to array
$a = array('a' => 'abc') + ($condition ? array('b' => 'xyz') : array());
Related Topics
Saving File Using Curl and PHP
Swap Two Words in a String PHP
Add a Shipping to an Order Programmatically in Woocommerce 3
How to Examine Defined Constants in PHP
Gmail API: 400 Bad Request When Trying to Send an Email (PHP Code)
How to Ensure I Caught All Errors from MySQLi::Multi_Query
PHP Fatal Error: Call to Undefined Function Mssql_Query()
PHP and Regexp to Accept Only Greek Characters in Form
Calculate the Geo Position at Given Time
Get/Set Dpi with PHP Gd/Imagick
Fatal Error: Uncaught Argumentcounterror: Too Few Arguments to Function
Symfony: How to Refresh the Authenticated User from the Database
Asynchronous Http Requests in PHP
How to Stop Curl from Using 100 Continue
In PHP, How to Generate a Big Pseudo-Random Number