How can I remove all data in an array - PHP
Get the solution ↓↓↓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);
}
Answer
Solution:
When you want to clear the complete array, why not usingunset($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 = [];
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: regex stop at first match
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.