Reputation: 25
<?php
$s1="";$s2="qwe";$s3="zxc";
if(!empty($s1))
{
$result=$s1;
}
else
{
if(!empty($s2))
{
$result=$s2;
}
else
{
$result=$s3;
}
}
echo "$result";
?>
Is there any possible code, probably of 1-2 lines, replacing the above mentioned code, I remember something like using "or" operator to do what I am doing with this code.
Upvotes: 2
Views: 90
Reputation: 57322
$result = $s1 ? $s1 : ($s2 ? $s2 : $s3);
why use this ?
since it reduce the complicity of the program
Note: The ternary operator is evaluated from left to right. So if you don't group the expressions properly, you will get an unexpected result
Upvotes: 1
Reputation: 829
Use this code:
<?
$s1="";
$s2="qwe";
$s3="zxc";
echo $result = ($s1!="") ? $s1 : ( ($s2!="") ? $s2 : $s3);
?>
Output: qwe
It's ternary operator. If you have $s1 as not empty then it returns $s1 or else again checks the condition for $s2 if it also empty then it returns $s3.
Upvotes: 0
Reputation: 137320
$result = $s1 ? $s1 : ($s2 ? $s2 : $s3);
Or even shorter, if you have PHP >5.3:
$result = $s1 ?: ($s2 ?: $s3);
More: PHP Manual part about Ternary Operator
Upvotes: 6
Reputation: 2820
Try conditional the assignment operator:
$result = !empty($s1) ? $s1 : ( !empty($s2) ? $s2 : $s3 );
Upvotes: 1