drxpt06820
2016-09-22 16:02
浏览 35
已采纳

PHP如果$ var null则返回$ var2

I havent been able to find an answer to this:

My code works like this:

echo ' <p> '.$test2.'</p> ';

I want to make $test2 change if it is null i have tried the following code and bunch of other and it just breaks the page

$test2 = if(empty($price)){ return $pstatus};

Any help would be apprteciated

UPDATE I have modified my code, now it returns the price but if the price is empty its returning nothing when it should return the $pstatus

so $price is say 625000 is that variable is empty it should return sold from the $pstatus variable

$price = number_format($p->meta_box->REAL_HOMES_property_price);
$fimage = $p->better_featured_image->media_details->sizes->medium->source_url;
$ptitle = $p->title->rendered;
$pdesc = $p->excerpt->rendered;
$plink = $p->link;
$pstatus = $p->pure_taxonomies->{"property-status"}[0]->name;
$test2 = $pstatus ? $price : $test2;
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dptgpyl61857413 2016-09-22 16:05
    已采纳

    You can do it inline:

    $test2 = $price ? $pstatus : $test2;
    

    If you need to assign "$price" to "$test2" and if there is no price then assign "$pstatus":

    $test2 = $price ? $price : $pstatus;
    
    点赞 打赏 评论
  • dshu1235 2016-09-22 16:14

    I would use is_null(), if as you say you actually want to check for null

      $test2 = !is_null( $price ) ? $pstatus : $test2;
    

    want to make $test2 change if it is null i have

    Be aware that when checking the value with == PHP will see 0, 0.0, false, null and a few other things as false. If price is ever 0 it would be false, which may or may not be what you want or expect.

    You can also check for $price === null Three equals checks for type as well as value being the same.

    点赞 打赏 评论

相关推荐 更多相似问题