简体   繁体   中英

Two loop foreach and unset

<?php

$array = array(a,s,d,f,g,h,j,k,l);

foreach($array as $i => &$a){
 foreach($array as $k => &$b){
    if($k = 4){
     unset($array[1]);
    }
 }

 echo $a . "\n";
}

print_r($array);

CODEPAD: http://codepad.org/UoWhrIkv

Why in this example echo show me only "a" and print_r show all good? Is possible to make good showing in loop with echo ?

I am not sure if your trying to have strings in the array or constants, but strings should be formatted like this.

$array = array('a','s','d','f','g','h','j','k','l');

Another thing you have wrong is your if statement

if($k == 4)

You need to use the double equal sign to compare, a single = sign is used for assignment.

Could you also provide exactly what you are trying to do here, because your code has some formatting issues off the bat, which could be why a was the only one printing.

Why in this example echo show me only "a" and print_r show all good?

When you modify an array you are iterating over in foreach Docs (here you remove an element), the behaviour of foreach might give you unexpected things. The note from the manual page says:

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.


Is possible to make good showing in loop with echo?

Yes, but it depends on what you try to achieve. As you have not specified what "good showing" actually means, we can only guess:

  • Assign $array to a new variable, and use that variable within the foreach s.
  • -OR- Don't use the references &$a and &$b , just use $a and $b .
  • -OR- Save which elements to delete and skip those within the iteration.
  • -OR- ...
  • -OR- even echo "good\\m"; ?

A working code-example could look like this ( Demo ):

$array = array('a','s','d','f','g','h','j','k','l');

foreach ($array as $i => &$a) {
    echo "$a\n";
}

print_r($array);

Two problems here:

The first is you're using = instead of == in this line:

if($k = 4){

The second is your logic, as when your inner loop iterates over the same array, it will repeatedly unset $array[1] .

That does not influence the inner foreach, but the outer one. So echo $a; has a chance to print once only.

Changing your if statement to:

if($k == 4){
  unset( $b);
}

Made the echo $a print the entire array (assuming that's what you're going for).

因为您使用的是引用&$a&$b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM