Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

if statement - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...