Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one make an assignment on conditional statement in php?

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

if(siteName_err = isValid("sitename", $_POST['sitename'], false))
{
    $siteName = $_POST['sitename'];
}
like image 912
Afamee Avatar asked Feb 03 '10 23:02

Afamee


People also ask

Can we use assignment operator in if condition?

Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)

What is the purpose of PHP conditional statement?

Conditional statements are used to perform different actions based on different conditions.

Can we assign inside if statement?

Yes, you can assign the value of variable inside if.


1 Answers

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.

like image 109
Aistina Avatar answered Oct 13 '22 23:10

Aistina