user2287208
user2287208

Reputation:

php update value in multidimensional array not by reference

I know that this is a similar question: Updating a Multidimensional Array in PHP

but is different my problem:
I have a multidimensional array and I want to check if a value inside it is equal another, if tue update value.

I have tried in this way:

$room_id = '1205222__1763659__386572_1';

foreach($cart as $c){
        if($c['item_type'] == 'hotel'){
            foreach($c as $key => $value){
                if(substr($key, 0, 7) == 'room_id'){
                    if($value == $room_id)  {
                        $c[$key] = '';
                    }                      
                }
            }
        }
    }

This is an example of my array:

array() {
  [0]=>
  array() {
    ["item_type"]=> "hotel"
    ["room_id_0"]=> "1205222__1763659__386572_1"
    ["room_id_1"]=> "1205222__1763659__386572_2"
  },
  [1]=>
  array() {
    ["item_type"]=> "hotel"
    ["room_id_0"]=> "1205222__1763659__386572_3"
    ["room_id_1"]=> "1205222__1763659__386572_4"
  }
}

I have checked if the conditions work right and yes, but when I make the assignment and after print the array again the array isn't changed.

Can someone help me?

Thanks

Upvotes: 0

Views: 1497

Answers (2)

martinczerwi
martinczerwi

Reputation: 2847

You can call foreach with passing $c by reference, like this:

foreach($cart as &$c){
...

This should let you change the value of the item.

To take it a step further, you could also pass $value by reference, and then change its value by modifying $value:

// Notice &$c
foreach($cart as &$c){
    if($c['item_type'] == 'hotel'){
        // Notice &$value
        foreach($c as $key => &$value){
            if(substr($key, 0, 7) == 'room_id'){
                if($value == $room_id)  {
                    // Instead of $c[$key]
                    $value = '';
                }                      
            }
        }
    }
}

Upvotes: 1

Liam Sorsby
Liam Sorsby

Reputation: 2982

this won't work as you are changing $c which is a copy of the array $cart. you would need to get the array key of the first array value and the array key of the second array and then update:

try this

foreach($cart as $a => $c){
        if($c['item_type'] == 'hotel'){
            foreach($c as $key => $value){
                if(substr($key, 0, 7) == 'room_id'){
                    if($value == $room_id)  {
                        $cart[$a][$key] = '';
                    }                      
                }
            }
        }
    }

Upvotes: 3

Related Questions