i have a question about shorten if else statement. I am trying to make a weather application using OpenWeatherMap api. But i don't like those icons. I want to change the icons like this:
if($desc == 'clear sky'){
$weather_icon = 'clear_sky.png';
}else
if($desc == 'few clouds'){
$weather_icon = 'few_clouds.png';
}else
if($desc == 'scattered clouds'){
$weather_icon = 'scattered_clouds.png';
}else
if($desc == 'broken clouds'){
$weather_icon = 'broken_clouds.png';
}else
if($desc == ''){
.....
}
......
So my question is how can i do this with shorten if else or do you have any idea to use different thinks?
Arrays are the glue that holds the universe together (if the universe is written in PHP).
$map = [
'clear sky' => "clear_sky.png",
'few clouds' =>"few_clouds.png",
'scattered clouds' => 'scattered_clouds.png'
'broken clouds' => 'broken_clouds.png'
];
if (isset($map[$desc])) {
$weather_icon = $map[$desc];
}
This allows you to also map unrelated words with image names as well as multiple words to the same image.
If your weather patterns are predictable, you can just use a one liner:
$img = str_replace ( ' ' , '_', $desc ) . '.png';
However if you have a list that you cannot just alter dynaically you can use this:
$descriptions = [
'clear sky'=>'clear_sky',
'few clouds'=>'few_clouds',
'scattered clouds'=>'scattered_clouds',
'broken clouds'=>'broken_clouds',
];
$defaultImg = 'some_empty';
$img = !empty($desc) ? $descriptions[$desc] : $defaultImg;
$img = $img . 'png';
Since your description matches what you're looking for you could do this.
if (
in_array(
$desc,
array(
'clear sky',
'few clouds',
'scattered clouds',
'broken clouds'
)
)
) {
$weather_icon = str_replace(' ', '_', $desc) . '.png';
}
Another option would be to use a map, they they don't always match.
$map = [
'clear sky' => 'clear_sky.png',
'few clouds' => 'few_clouds.png',
'scattered clouds' => 'scattered_clouds.png',
'broken clouds' => 'broken_clouds.png',
'thunderstorm with light rain' => 'few_clouds.png',
];
// $api['icon'] references the original icon from the api
$weather_icon = array_key_exists($desc, $map) ? $map[$desc] : $api['icon'];
<?php
$desc = "clear sky";
$weather_icon = str_replace(" ","_",$desc).".png";
echo $weather_icon;
?>
It looks like you have a some fixed notation. You could use this:
<?php
$desc = 'clear sky';
convertDescriptionToImage( $desc );
function convertDescriptionToImage( $description )
{
$arrayCodes = ["clear sky", "few clouds"];
if ( TRUE == in_array( $description, $arrayCodes ) )
{
return str_replace( " ", "_", "$description.png" );
}
die( "$description not found" );
}