chillichief
chillichief

Reputation: 1212

JavaScript "or"-functionality in PHP

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.

Upvotes: 1

Views: 56

Answers (2)

muued
muued

Reputation: 1676

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'];

Upvotes: 2

Denis Frezzato
Denis Frezzato

Reputation: 968

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'];

Upvotes: 1

Related Questions