Corentin Branquet
Corentin Branquet

Reputation: 1586

Foreach into PHP array

I've this these array values :

$cart_item['addons'][0]['price'] = '52';
$cart_item['addons'][1]['price'] = '34';
$cart_item['addons'][2]['price'] = '12';
......
....

I want that each values are at 0 like :

$cart_item['addons'][0]['price'] = '0';
$cart_item['addons'][1]['price'] = '0';
$cart_item['addons'][2]['price'] = '0';
....
...

So I try this code :

for ($i=0; $i > 0 ; $i++) { 
    $cart_item['addons'][$i]['price'] = '0';
}

But it does not work. Thanks for your help !

Upvotes: 1

Views: 69

Answers (5)

Henders
Henders

Reputation: 1215

There are three parts to your for loop: for(counter | test | action){}. It might be useful for you to look at this guide about for loops. You initialise your variable:

$i = 0;

then you do a logical check (the test part):

$i > 0;

If we substitute the the variable ($i) for the value it holds (0) we get:

0 > 0

which will never be true and thus you will never get to the final part (action) of the for loop:

$i++;

Instead you could make it loop until it has moved through your entire array like this:

$elementCount = count(cart_item['addons']);
for($i=0; $i < $elementCount; $i++){ 
    $cart_item['addons'][$i]['price'] = '0';
}

Each time it loops we add one to $i until we reach the stopping condition where $i is no longer less than the number of items in the array.

It's also worth noting that PHP has a number of functions that help working with arrays.

Upvotes: 0

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

Try this simple solution:

$count=count($cart_item['addons']);
for($i=0; $i<$count;$i++ ){
  $cart_item['addons'][$i]['price'] = '0';
}

Upvotes: 4

Kevin Kopf
Kevin Kopf

Reputation: 14230

If your array is big enough, putting count() function inside for loop is being a crazy coconut. It will be much, much slower. Please use the count outside the loop:

$count = count($cart_item['addons'])

for($i=0; $i<$count;$i++ ){
 $cart_item['addons'][$i]['price'] = '0';
}

Upvotes: 2

PunchyRascal
PunchyRascal

Reputation: 380

You can iterate over $cart_item['addons'], like so:

foreach ($cart_item['addons'] AS $key => &$value) {
    $value['price'] = 0;
}

(Your code does not get executed, because $i is never changed and so is never > 0)

Also note that you need to use the reference (&$value) when changing the array in foreach loop.

Upvotes: 0

KiwiJuicer
KiwiJuicer

Reputation: 1972

You have to loop more often to achive this:

foreach($cart_item['addons'] as &$addons {
    foreach($addons as &$addon) {
          $addon['price'] = 0;
    }
}

Upvotes: 1

Related Questions