How do I make this into a function? I’m doing the same thing twice…
I tried to make the code as concise (given my newbie skills) as possible. If there’s a better way to check if file exists with less code, or do anything with less code, please suggest it.
As you can see, I need to
1) check the file exists
2) make it night, if it’s night
3) check if that exists
4) get the key – for some reason, the incoming text will NOT MATCH string key 100%, so that’s why I’m using string match instead of =
$today_desc_stripped = trim($today_desc);
foreach ( $icon as $k => $v ) {
similar_text($today_desc_stripped, $k, $p);
if ( $p > 90) {
$today_desc = $k;
break;
}
}
$today_icon = $icon[$today_desc];
// if it's past 6 pm, set temp icon to night icon
if ( file_exists("scripts/weather_icons/".$today_icon.".png") ) { // make sure file exists
if ( $time >= 6 ) {
$temp = $today_icon."_night";
if ( file_exists($temp) ) {
$today_icon = $temp;
}
}
} else {
//if file doesn't exist
$today_icon = "dunno";
mail($to,$subject,$message."195: Icon array on Line 20 is missing assignment for ".$today_desc_stripped);
}
$fourday_desc_stripped = trim($fourday_desc);
foreach ( $icon as $k => $v ) {
similar_text($fourday_desc_stripped, $k, $p);
if ( $p > 90) {
$fourday_desc = $k;
break;
}
}
$fourday_icon = $icon[$fourday_desc];
// if it's past 6 pm, set temp icon to night icon
if ( file_exists("scripts/weather_icons/".$fourday_icon.".png") ) { // make sure file exists
if ( $time >= 6 ) {
$temp = $fourday_icon."_night";
if ( file_exists($temp) ) {
$fourday_icon = $temp;
}
}
} else {
//if file doesn't exist
$fourday_icon = "dunno";
mail($to,$subject,$message."218: Icon array on Line 20 is missing assignment for ".$fourday_desc_stripped);
}
Here’s the steps that you need to follow:
You can either put your error checking inside the function or outside. As there were several variables that were set up in our current scope simply for your error email, I left it outside of the function:
And for the function itself: