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.
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.
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.
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 _ ).
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.
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"; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With