Dani GTA Dani GTA - 3 months ago 10
PHP Question

PHP, foreach only output "1"

The code is simple but the output is confusing me.

$dirnames = scandir($dir);


The array of $dirnames :


Array ( [0] => . [1] => .. [2] => 0 [3] => 001 [4] => 009_1


foreach ($dirnames as $name) {
if($name =! NULL){
echo $name;
}}


The output of echo is:


11111


After the loop.

Answer

The error is in

if($name =! NULL)

You should change it to:

if($name != NULL)

The first of the two is an assignment. It assigns to $name the boolean negation of null which is true, and so the if condition is always fufilled. Finally, the boolean true is echoed as 1.

The second of the two is a comparison, which is what you intended.