1

I have the following Code in PHP

if($row["phone"])
  $phone = $row["phone"];
else
  $phone = $row["mobile"];

In JavaScript I could simply write

phone = row.phone || row.mobile;

which is much easier to write, and looks much better. If I try the same in PHP it would simply return true

$phone = $row["phone"] || $row["mobile"];
echo $phone;     // 1

Is there any operator in PHP that offers me the same functionality as the in JavaScript? I tried the bitwise or |, but that only works sometimes and sometimes i get really weird results.

chillichief
  • 1,164
  • 12
  • 22

2 Answers2

2

have a look at this answer. You can use the elvis operator like this:

$phone = $row['phone'] ?: $row['mobile'];

This would be shorter than

$phone = $row['phone'] ? $row['phone'] : $row['mobile'];
Community
  • 1
  • 1
muued
  • 1,666
  • 13
  • 25
1

In PHP, the logical operators always return a boolean value, so you have to do the job as you've done in your question. You can also write using a ternary operator:

$phone = $row['phone'] ? $row['phone'] : $row['mobile'];
Denis Frezzato
  • 957
  • 6
  • 15