Mr.Smithyyy Mr.Smithyyy - 1 year ago 44
PHP Question

Echo different images depending on array value

I want to echo a different image depending on if a key exists or not.

Here is an example of the array I'm using

["Person"] => array(11) {
["id"] => int(38482818123)
["weight"] => int(140)
["height"] => int(65)
["Name"] => array(2) {
["firstname"] => string(4) "John"
["lastname"] => string(5) "Smith"

So the name field isn't always there. I need to show
image a
if the name is there and
image b
if there is no name.

What I've tried:

foreach($personArray as $person)
if ($person['Name'] != '')
echo "<img src='image-a.png'>";
echo "<img src='image-b.png'>";

Now the problem I have is that even though the person has a name, I'm seeing both images on the page instead of just
image a

I have also tried using
array_key_exists("Name", $personArray);
but for some reason I am getting
as a result.


Answer Source

You need to use empty() like below:-

    //image a code
    //image b code