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.

0

2 Answers 2

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

Ok now this is EXACTLY, what i was looking for. Short and sweet
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'];

4 Comments

this ? seems to be the one im looking for. can you give a short explanation on how exactly this works?
@chillichief that's ternary operator. google about it.
ok i got it. it is literally just a shorhand version of the code i wrote. THX
It is basically shorthand for if--else. @chillichief

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.