1

Hello there do you know a way for writing this in PHP without repeating the variable name?

if($abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"]!=="") {
    echo $abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
} else if($abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"]!=="") {
    echo $abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
} else if($abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"]!=="") {
    echo $abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"];
}

Of course you can write

$a = $abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
$b = $abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
$c = $abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"];

if($a) { echo $a; } else if($b) { echo $b; } else if ($c) { echo $c; }

This is a bit shorter but I still wonder if there is some syntactical nice thing to write it without variable repetition.

Ternary operator does not solve the problem because of the "elseif" I think.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Blackbam
  • 17,496
  • 26
  • 97
  • 150

3 Answers3

4

This should work for you:

Just loop through all indexes, which you want to check and print them if they pass the if statement, e.g.

$indexes = ["blaBlaBlaBlaBlaBlaBlaBlaBlaBla", "evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla", "stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"];

foreach($indexes as $key) {
    if($abcdefg[$key] !== "") {
        echo $abcdefg[$key];
        break;
    }
}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

You can do a variable declaration in the if condition:

if(($var = $abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"]) !== "") {
    echo $var;
}
bitWorking
  • 12,485
  • 1
  • 32
  • 38
0

What about declaring a function for the ... hmmm ... functionnality?

function echoNotEmpty($s)
{
    if ($s !== '') echo $s;
}
echoNotEmpty($abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"]);
echoNotEmpty($abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"]);
echoNotEmpty($abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"]);

Or even shorter:

echo $abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
echo $abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
echo $abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"];

I mean, if you don't want to echo empty string and you still echo them, who cares?

Mat
  • 2,134
  • 1
  • 18
  • 21
  • 1
    The problem is the "elseif" (there are maybe two strings which are not empty, and only the first should be echoed). – Blackbam Jun 30 '15 at 18:34