Reputation: 23
I'm accessing an API which is returning the value of an array. I want a image to be displayed based on the result. For example if the div contains "above average" then display an image called aboveAverage.png.
echo $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'];
This results is "Above Average" How can I display a particular image to correspond to this?
Something like ->
if Div "crime_level" = above average then:
display aboveAverage.png
I'm pretty new to PHP, sorry i'm a noob.
Upvotes: 2
Views: 3927
Reputation: 6968
If the values of
$cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']
are finite and you happen to know them all you could use an associative array, where the key would be the value returned by the API and the corresponding value to that key would be the file name of the image you want to display. Something like:
$images = array(
'Above Average' => 'aboveAverage.png',
'Below Average' => 'belowAverage.png',
// etc
);
$img = 'default.png'; // set a default image file
$crimeRate = $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'];
if (array_key_exists($crimeRate, $images)) {
$img = $images[$crimeRate];
}
// output the image
echo "<img src=" . $img . " />";
Upvotes: 3
Reputation: 3288
Use a case selecting switch
switch ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']) {
case "Above Average":
$image = "aboveAverage.png";
break;
case "Below Average":
$image = "belowAverage.png";
break;
default:
$image = "unknown.png";
};
echo "<img src=\"$image\" />";
Doing it this way allows you to remove your logic from your display by setting the variable as $image so you're not having to update 20 different potential image tags. It also allows you to cater for many different cases of the string without ending up lost in if then else hell
Upvotes: 3
Reputation: 28906
There are two parts to your question. The first is how to compare the array element to a string. This is accomplished like this:
if ( $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'] == "Above average" ) {
// The second part of your question is how to display an image.
echo '<img src="aboveAverage.php" />;
}
There are other ways to display images via PHP scripts, such as setting an appropriate header and dumping the image content directly. If you are looking for such a solution, see Output an Image in PHP.
Upvotes: 1
Reputation: 14681
A simple if and echo will do:
if ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'] == "above average") {
echo "<img src='aboveAverage.png' />
}
Upvotes: 0
Reputation: 7784
Here is some approach:
$toDisplay = array("Above average", "Average") ;
if (in_array($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'], $toDisplay)){
echo "<img src='image.png' alt='image'/>" ;
}
Upvotes: 0