Alex Rivera | Logout

Can I define a variable in a PHP if condition?

Asked 2011-07-19T01:38:43.010
40

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.

Edit
Report

1 Answer

5

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.

answered 2011-07-19T01:52:06.140

Your Answer