Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a variable in a PHP if condition?

For example, can I do:

if ($my_array = wp_get_category($id)) {     echo "asdf"; } else {     echo "1234"; } 

If nothing is returned by the function, I want to go into the else statement.

like image 909
Casey Avatar asked Jul 19 '11 01:07

Casey


People also ask

Can you define variables in IF statements?

Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.

How do you use a variable outside of an if statement in PHP?

Right now $uname is only in scope within the if statement, once you leave the if statement the variable no longer exists. PHP has no block scope for variables, so they are available until the end of the function once they have been assigned a value.

How do you define a variable in PHP?

All variables in PHP start with a $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character _ . A variable name cannot start with a number. A variable name in PHP can only contain alpha-numeric characters and underscores ( A-z , 0-9 , and _ ).

DO IF ELSE blocks define a scope?

No, it does not. If blocks remain scoped to their containers. Your function B is undefined because the code which defines it never gets executed when blocked by the if statement. However, once the if statement is removed, the code defining the function is executed, defining the function.


2 Answers

Yes, that will work, and the pattern is used quite often.

If $my_array is assigned a truthy value, then the condition will be met.

CodePad.

<?php  function wp_get_category($id) {    return 'I am truthy!'; }  if ($my_array = wp_get_category($id)) {     echo $my_array; } else {     echo "1234"; } 

The inverse is also true...

If nothing is returned by the function, I want to go into the else statement.

A function that doesn't return anything will return NULL, which is falsey.

CodePad.

<?php  function wp_get_category($id) { }  if ($my_array = wp_get_category($id)) {     echo $my_array; } else {     echo "1234"; } 
like image 71
alex Avatar answered Sep 22 '22 02:09

alex


This is in fact a common pattern and will work. However, you may want to think twice about using it for more complex cases, or at all. Imagine if someone maintaining your code comes along and sees

if ($x = one() || $y = two() && $z = three() or four()) {  } 

It might be better to declare the variables before using them in the conditional.

like image 41
Explosion Pills Avatar answered Sep 21 '22 02:09

Explosion Pills