Array_walk in PHP cannot unset reference arrays, do you have any questions about the code?

Source: Internet
Author: User
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.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.