Osvaldo Parra
Osvaldo Parra

Reputation: 21

PHP add element to array only when condition is true

I have this code:

...............................................
               'Detalle' => array()
    ];


foreach ($cart as $line => $item) {

//check condition
if (strtolower($item['description']) === 'something') {
    $cond = true;
} else {
    $cond= false;
}

$ab['Detalle'][]=array(     

    'NmbItem' => $item['name'],
    'QtyItem' => (int)$item['quantity'],
    'PrcItem' => $item['price']     

);

if ($cond){
     $array2 = array('IndExe' => 1);
     array_merge($ab['Detalle'],$array2);
}

}

How can I add 'IndExe' to $ab['Detalle'] array only when the condition is true? I tried array_merge, array_merge_recursive but nothing.

IndExe only can be 1, another value like 0 or null is not possible. I tried:

  $ab['Detalle'][]=array(        

        'NmbItem' => $item['name'],
        'QtyItem' => (int)$item['quantity'],
        'PrcItem' => $item['price']   
        'IndExe' => ($cond? 1 : 0 )     

    );

but when cond = false then IndExe = 0, is not what I need. IndExe must be added only when cond = true.

Upvotes: 0

Views: 650

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

The problem is the dynamically appended [] element. You could use the index $line:

foreach ($cart as $line => $item) {

    $ab['Detalle'][$line] = array(
        'NmbItem' => $item['name'],
        'QtyItem' => (int)$item['quantity'],
        'PrcItem' => $item['price']     
    );    
    if (strtolower($item['description']) === 'something') {
        $ab['Detalle'][$line]['IndExe'] = 1;
    }
}

If $line doesn't give the indexes you want (but they shouldn't matter), then:

$ab['Detalle'] = array_values($ab['Detalle']);

Unless you're using $cond again later in the code, you don't need it.

Upvotes: 0

Aydin4ik
Aydin4ik

Reputation: 1935

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;

Upvotes: 3

Related Questions