rai nalasa
rai nalasa

Reputation: 859

Add value on array if it exist

I wanted to add a value on my array if it exist.If not then create a new one.

  $orders = array(
              array("qty" => 3,"piece_type"=> "Documents (Up to 1kg)"),
              array("qty" => 2,"piece_type"=> "Documents (Up to 1kg)"),
              array("qty" => 4,"piece_type"=> "Large (10-20kg 150cm)")
              );

$sizes = array(
    "Documents (Up to 1kg)"=>10,
    "Large (10-20kg 150cm)"=>20
);

$wpc_total_cost = array();
$i = 0;

foreach( $orders as $value )
{     
  $i++; 
  $wpc_total_cost[$value['piece_type']] += $value['qty'] * $sizes[$value['piece_type']];
}

print_r($wpc_total_cost);

I tried array_exist I don't quite get the logic.

my error :

NOTICE Undefined index: Documents (Up to 1kg) on line number 21

NOTICE Undefined index: Large (10-20kg 150cm) on line number 21
Array ( [Documents (Up to 1kg)] => 50 [Large (10-20kg 150cm)] => 80 )

Upvotes: 0

Views: 46

Answers (2)

Charles
Charles

Reputation: 1122

Try using array_key_exists. I made a variable named $cost just so the formula wasn't repeated in two places.

$orders = array(
    array("qty" => 3,"piece_type"=> "Documents (Up to 1kg)"),
    array("qty" => 2,"piece_type"=> "Documents (Up to 1kg)"),
    array("qty" => 4,"piece_type"=> "Large (10-20kg 150cm)")
);

$sizes = array(
    "Documents (Up to 1kg)"=>10,
    "Large (10-20kg 150cm)"=>20
);

$wpc_total_cost = array();
$i = 0;

foreach( $orders as $value )
{
    $i++;

    $cost = $value['qty'] * $sizes[$value['piece_type']];

    if(array_key_exists($value['piece_type'], $wpc_total_cost)){
        $wpc_total_cost[$value['piece_type']] += $cost;
    } else {
        $wpc_total_cost[$value['piece_type']] = $cost;
    }
}

print_r($wpc_total_cost);

Upvotes: 1

Iłya Bursov
Iłya Bursov

Reputation: 24146

the problem is in this line:

$wpc_total_cost[$value['piece_type']] += $value['qty'] * $sizes[$value['piece_type']];

operation += actually means this:

$wpc_total_cost[$value['piece_type']] = $wpc_total_cost[$value['piece_type']] + $value['qty'] * $sizes[$value['piece_type']];

Note, that we're using $wpc_total_cost[$value['piece_type']] on right side of the expression, it means that it should be defined, but on first iteration of foreach loop is does not exists.

One quick fix is to use:

if (!isset($wpc_total_cost[$value['piece_type']]))
    $wpc_total_cost[$value['piece_type']] = 0;
$wpc_total_cost[$value['piece_type']] += $value['qty'] * $sizes[$value['piece_type']];

Upvotes: 0

Related Questions