Reputation: 57
Hope all is well.
I'm wanting to display a series of badges which would display different images based on a field which contains a specific string. For example, something like this (although I'm aware that this is probably not correct)
<?php if (stripos($business, "local") !== false)
echo "badge-icon1.png"; ?>
<?php if (stripos($business, "interstate") !== false)
echo "badge-icon2.png"; ?>
<?php if (stripos($business, "national") !== false)
echo "badge-icon3.png"; ?>
<?php if (stripos($business, "international") !== false)
echo "badge-icon4.png"; ?>
I'm familiar with the stripos function, although I'm not sure whether or not it is suitable for an array of alternative scenarios based on if one field contains one of a few string options.
Is there an alternative method which may be a little more suitable?
Thank you for your assistance!
Upvotes: 1
Views: 34
Reputation: 147176
stripos
isn't really suitable here as it will match national
in both national
and international
. If the entire $business
string is the word local
or interstate
etc. you might find an array easier to work with:
$badges = array('local' => 'badge-icon1.png',
'interstate' => 'badge-icon2.png',
'national' => 'badge-icon3.png',
'international' => 'badge-icon2.png'
);
echo $badges[$business] ?? '';
If $business
might have uppercase characters in it (e.g. Local
), use strtolower($business)
as the array index:
echo $badges[strtolower($business)] ?? '';
Also, if you want to have a default image for when $business
doesn't match one of the 4 names, you can put that in the echo
:
echo $badges[$business] ?? 'badge-placeholder.png';
Upvotes: 2