views:

154

answers:

4

Can you make an assignment on conditional statement in php as so:

if(siteName_err = isValid("sitename", $_POST['sitename'], false))
{
    $siteName = $_POST['sitename'];
}
+1  A: 

Yes.

Honestly, why don't you try it out? Languages where you're not allowed to do this sort of thing usually generate compiler/parser errors.

PHP takes most of its basic syntactic elements from C, which includes that every assignment returns a value. Therefore this is valid.

Joey
+1 for "try it out" - it would surely have been far quicker
Rob
+2  A: 

Yah, you can do that.

If you're asking because you tried it and got a crazy error, try making siteName_err a valid variable name by putting a dollar sign $ before it.

yjerem
A: 

Yes sure and you can do also the same for while constructs

streetparade
+1  A: 

Yes.

I think the most common use scenario for this is when using MySQL. For example:

$result = mysql_query("SELECT username FROM user");
while ($user = mysql_fetch_assoc($result)) {
  echo $user['username'] . "\n";
}

This works because $user is the result from the assignment. Meaning, whatever is stored in your assignment, is then used as the conditional. In other words,

var_dump($i = 5);

// is equivalent to

$i = 5;
var_dump($i);

Both will print int(5), obviously.

Aistina