PHP Variable Assignment Within If Statement

7th June 2009 - 3 minutes read time

The usual practice when checking for the return value of functions is to run the function and store the value in a variable, and then test that variable. Here is an example of that process using the strstr() function.

  1. $string = 'abcde';
  2. $var = strstr($string, 'f');
  3. if ( false !== $var ) {
  4. var_dump($var);
  5. } else {
  6. var_dump($var);
  7. }

This code will output "bool(false)" as that was the return value of the strstr() function.

There is another way to write the same code within a single if statement. The following example assigns the variable and checks the return value in a single line of code.

  1. $string = 'abcde';
  2.  
  3. if ( false !== $var = strstr($string, 'f') ) {
  4. var_dump($var);
  5. } else {
  6. var_dump($var);
  7. }

This code will output "bool(false)" again as this has the same function as the previous example.

There is one problem with assigning variables in this way, and this is that you can only do one. If you try to assign more than one variable at a time you will find that everything but the final variable will turn out to be the outcome of the boolean comparison. Take the following example, which uses the same $string variable as the other examples.

  1. if ( false !== $var1 = strstr($string, 'a')
  2. && false !== $var2 = strstr($string, 'b')
  3. && false !== $var3 = strstr($string, 'c') ) {
  4. var_dump($var1, $var2, $var3);
  5. }

The output of this code will be as follows:

bool(true) bool(true) string(3) "cde"

The first two comparisons come out as true and so $var1 and $var2 are assigned boolean values of true. The final comparison is the only one that is assigned the expected value. This might be a bug in PHP, but as this is a non-standard way of assigning variables I don't think many people have come across it.

Comments

Permalink
Great blog, reading it through RSS feed as well

James Bower (Mon, 09/07/2009 - 21:17)

Permalink
I dare say the last example is correct behaviour. This is what variables are actually assigned.
  1. ... $var1 = (strstr($string, 'a') && false !== $var2 = strstr($string, 'b') && false !== $var3 = strstr($string, 'c'))
  2. ... $var2 = (strstr($string, 'b') && false !== $var3 = strstr($string, 'c'))
to get expected behaviour all one needs is enclosing assignments within ().
  1. if ( false !== ($var1 = strstr($string, 'a'))
  2. && false !== ($var2 = strstr($string, 'b'))
  3. && false !== ($var3 = strstr($string, 'c'))) {
  4. var_dump($var1, $var2, $var3);
  5. }
also by doing that - in theory - you're helping compiler (for tiny speedup) so it doesn't need to find out operator precedence, just eval from insidemost statement(s).

Mirek Suk (Tue, 09/28/2010 - 12:08)

Permalink
Thanks for that Mirek, I did wander what was going on but kind of forgot about this article once I had published it. I really appreciate the input :)
Permalink
I had done this in the past successfully but have since forgotten the exact syntax. Thanks for this, it helped me tremendously.

Jim (Sun, 11/07/2010 - 23:09)

Permalink

This works too:

  1. if( !($val = $arg) )
  2. {
  3. $val = 'default';
  4. }

Frank (Mon, 05/02/2011 - 17:52)

Permalink
Thanks guys!!

Vishal (Sun, 05/17/2015 - 09:24)

Permalink
This is absolutely terrible practice to use this in your code. It is also against generally accepted PSR standards: https://www.php-fig.org/psr/psr-2/#23-linesas it is combining 2 statements (declaration statement and expression statement) into one line.

Jesus (Tue, 03/20/2018 - 14:55)

Permalink
@Jesus Yes. I completely agree. I always split out the assignment operators from if statements. To be honest I'm not sure where I got this code orignally, but I think I found it in someone elses code that I had to alter at the time. Trying to figure out that mess at the time was a real pain, but I came across this strange behaviour and thought I would post about it.
Permalink

A gotcha worth highlighting, assigning a 0 is of course a falsy, so you can work around it as follows where NULL is returned when we really want to exit, and not on 0.

  1. while ( NULL !== ( $n = $this->getSomeIntIndex( )) )
  2. {
  3. // do something with $n
  4. }

 

Russ (Fri, 05/31/2019 - 18:18)

Permalink

Hi, I need help with below code

How to create variable with if multiple statement in php and print
 

  1.     $selected_payment_option =  'if($payment_mode == "cod"){ echo "Cash on Delivery ";}
  2.                                             if($payment_mode == "stripe"){ echo "Stripe";}
  3.                                             if($payment_mode == "bank"){ echo "Bank";}';


and want to print as
 

$selected_payment_option 

 

Sam (Fri, 05/15/2020 - 21:30)

Permalink

Sam,

For fixed payment types, you may be better off to assign an array with the options, with the code as key, and display name as value. That array could be filled from a database query on payment types allowed, which would then pick up when you add a new option, you don't then have to re-code so much.

  1. $userPaymentSel = $_POST['user_payment_selection']; // Assuming user selected payment type is received here
  2.  
  3. $paymentTypes = array(
  4. 'cod'=>'Cash on Delivery',
  5. 'stripe'=>'Stripe',
  6. 'bank'=>'Bank'
  7. );
  8.  
  9. $selected_payment_option = $paymentTypes[$userPaymentSel];

That has no input validation etc, but might be a start.

Peter H (Fri, 06/05/2020 - 12:24)

Add new comment

The content of this field is kept private and will not be shown publicly.