Dani GTA Dani GTA - 1 year ago 107
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:


After the loop.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download