A newbie's question about variables in PHP

General discussions related to php

Moderators: macek, egami, gesf

shay
New php-forum User
New php-forum User
Posts: 3
Joined: Mon Nov 19, 2012 8:56 am

A newbie's question about variables in PHP

Postby shay » Thu Dec 06, 2012 10:25 am

Hi,

I copied-pasted the below script:

If you go over the script you would encounter this line "while ($file = readdir($dp))" which I totally understand except for one thing, where did the $file variable come from? I went over the whole script and didn't see where the $file variable was initialized (before it wasappeared in the whole loop of course).


could you please provide an explanation?

TIA

<?php
// function definition
// print names of files in a directory
// and its child directories
function printDir($dir, $depthStr='+') {
if (file_exists($dir)) {
// create directory pointer
$dp = opendir($dir) or die ('ERROR: Cannot open directory');
// read directory contents
// print names of files found
// call itself recursively if directories found
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
echo "$depthStr $dir/$file \n";
if (is_dir("$dir/$file")) {
printDir("$dir/$file", $depthStr.'+');
}
}
}
// close directory pointer
closedir($dp);
}
}
// print contents of directory
// and all children
if (file_exists('.')) {
echo '<pre>';
printDir('.');
echo '<pre>';
}
?>

User avatar
Barrikor
New php-forum User
New php-forum User
Posts: 16
Joined: Sun Dec 12, 2010 3:14 pm

Re: A newbie's question about variables in PHP

Postby Barrikor » Sat Dec 08, 2012 9:26 pm

while ($file = readdir($dp))

It's using = instead of == inside the condition. When you use = in a condition, the condition evaluates if the variable is true or false. It's really easy to accidentally create an infinite loop that way. Also if anyone sees it they usually assume that you typed it wrong and meant == instead, so if you use it you should add a comment to it.

In this case it kinda works since readdir() returns false when it's done reading the dir, BUT the example section of the documentation for readdir() clearly states not to do it this way.

shay
New php-forum User
New php-forum User
Posts: 3
Joined: Mon Nov 19, 2012 8:56 am

Re: A newbie's question about variables in PHP

Postby shay » Sun Dec 09, 2012 2:17 am

Thank you for the usable info


Return to “PHP General”

Who is online

Users browsing this forum: Yahoo [Bot] and 1 guest