Amanda Thompson Amanda Thompson - 4 months ago 7
PHP Question

Change the index of an array

I need help to change the index of an array.

I have this array:

$items = array('items' => array(
0 => array(
'item_id' => 1,
'item_amount' => 100,
),
1 => array(),
));


Now I want to remove the index, based on the value of
item_id
, but I don't know how to do this.

I've tried to do it as follows, but doesn't work.

foreach($items['items'] as $key) {
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($removeIndex);
}
}


How can I do this?

Answer

You need to use unset like this:

foreach($items['items'] as $index => $key) { // also get the index!
  $removeIndex = $key['item_id'] == 1;
  if($removeIndex) {
     unset($items['items'][$index]['item_id']); // specify path to that entry
  }  
}

See it run on eval.in.

To unset something in your nested array structure, you need to act on that array itself. unset($removeIndex) does not change the array, because that is a boolean value.

Removing the entire "row"

If your aim is to also remove the sub-array to which the item_id belongs (so including the item_amount and any other value in that sub-array), then just shorten the "path" in the unset statement:

foreach($items['items'] as $index => $key) { // also get the index!
  $removeIndex = $key['item_id'] == 1;
  if($removeIndex) {
     unset($items['items'][$index]); // specify path to that entry
  }  
}