1

I have an array with in which there is another array. I need to unset a index of the sub array.

array
  0 => 
    array
      'country_id' => string '1' (length=1)
      'description' => string 'test' (length=4)
  1 => 
    array
      'country_id' => string '2' (length=1)
      'description' => string 'sel' (length=5)
  2 => 
    array
      'country_id' => string '3' (length=1)
      'description' => string 'soul' (length=5)

Now i need to unset country_id of all the three index of the master array. I am using PHP and I initially thought unset will do until i realized my array is nested.

How can I do this?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
PHPlearner
  • 13
  • 3

4 Answers4

0
foreach ($original_array as &$element) {
  unset($element['country_id']);
}

why &$element?

Because foreach (...) will perform a copy, so we need to pass the reference to the "current" element in order to unset it (and not his copy)

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
0
foreach ($masterArray as &$subArray)
    unset($subArray['country_id']);

The idea is that you take each sub array by reference and unset the key within that.


EDIT: another idea, just to make things interesting, would be to use the array_walk function.

array_walk($masterArray, function (&$item) { unset ($item['country_id']); });

I'm not sure that it's any more readable, and the function call will make it slower. Still, the option is there.

Tom
  • 522
  • 3
  • 13
0
foreach($yourArray as &$arr)
{
   unset($arr['country_id']);
}
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
0

You need to use:

foreach ($array as &$item) {
  unset($item['country_id']);
}

but after loop you should really unset reference otherwise you might get into trouble so the correct code is:

foreach ($array as &$item) {
  unset($item['country_id']);
}
unset($item);
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291