The code is as follows:
$array = array(0 => 'bar', 1 => 'bat', 2=>'bar', 3=>'car', 4=>'buy',5=>'foo');array_walk($array, function($val,$key) use(&$array){ if(strpos($val, 'b')!==false){ unset($array[$key]); }}); var_dump($array);
Output:
array(3) { [1]=> string(3) "bat" [3]=> string(3) "car" [5]=> string(3) "foo" }
Reply content:
The code is as follows:
$array = array(0 => 'bar', 1 => 'bat', 2=>'bar', 3=>'car', 4=>'buy',5=>'foo');array_walk($array, function($val,$key) use(&$array){ if(strpos($val, 'b')!==false){ unset($array[$key]); }}); var_dump($array);
Output:
array(3) { [1]=> string(3) "bat" [3]=> string(3) "car" [5]=> string(3) "foo" }
Try PHP array_filter
php
$array = array(0 => 'bar', 1 => 'bat', 2=>'bar', 3=>'car', 4=>'buy',5=>'foo');array_walk($array, function($val,$key) use(&$array){ echo $val."\n"; if(strpos($val, 'b')!==false){ unset($array[$key]); }}); var_dump($array);
Output
barbarbuyarray(3) { [1] => string(3) "bat" [3] => string(3) "car" [5] => string(3) "foo"}
Output This $val
can be seen in the clues.
First time unset
Become
0 = ' bat ',
1 = ' Bar ',
2 = ' car ',
3 = ' buy ',
4 = ' Foo '
Array second traversal, reading data indexed to 1
So unset ($array [1]) is the bar
And so on
It is generally not recommended to remove elements from an array when traversing an array.
Will cause the iterator to point to confusion.
The general scenario is to put the data you want to delete into a new array. Then go through the array to delete and remove the original element.