-1

I'm trying to delete all the data in this array. I'm beginer

$data = array(
      ['id' => 1, 'name' => 'Alex'],
      ['id' => 2, 'name' => 'Max'],
      ['id' => 3, 'name' => 'George']
  );

I'm using this code to do it, but it doesn't work :(

foreach ($data as $item) {
     unset($item);
}
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
ChrisDLH
  • 123
  • 1
  • 2
  • 9

1 Answers1

0

When you want to clear the complete array, why not using unset($data)? Your code does not work they way as you expect it, because in your loop you are defining a new variable $item. You are then unsetting this variable $item which has no effect on original the values of your $data array. If you want to use a loop you need to define it like that:

foreach ($data as $index => $item) {
    unset($data[$index]);
}

This clears all values from $data but not unsetting the $data array itself. A more efficient way compared to the loop would be to just assign a empty array to $data like:

$data = [];
Amacado
  • 630
  • 5
  • 20