Reputation: 401
I need to know if there's a quickest and efficient way to display one or more images if $value == $string
For example: I have an cell which only contains 3 single string: 'r o g'
, if user put ro
it will output <img src="red.gif">
and <img src="orange.gif">
So it could be random if user insert gr
then it will display <img src="green.gif">
and <img src="red.gif">
Right now I can only think something like...
<?php $red = "<img src="red.gif">";
$orange = "<img src="orange.gif">";
if( $cell1 == $red ){ echo $red;}
if( $cell1 == $red && $orange ){ echo $orange.$red;}
etc...
This method might works but has to provide too many possibility and I believe there's a shorter and efficient to do that, but I haven't got any idea because still I'm learning PHP
Upvotes: 0
Views: 664
Reputation: 683
Here is the code that shows an example for 3 character inputs. $string can be the posted value.
$r = '<img src="red.gif">';
$y = '<img src="yellow.gif">';
$o = '<img src="orange.gif">';
$g = '<img src="green.gif">';
$string = 'ryo';
$length = strlen($string);
for ($i=0; $i<$length; $i++) {
echo ${''.$string[$i]};
}
Upvotes: 1
Reputation: 10975
How about this approach?
<?php
//define all your images here
$images = [
'r' => 'red.png',
'g' => 'green.png',
'b' => 'blue.png',
'y' => 'yellow.png',
'o' => 'orange.png'
];
function output($input, $images) {
$parts = str_split($input);
foreach ($parts as $part) {
if (isset($images[$part]))
echo '<img src="' . $images[$part] . '">';
}
}
echo "rgb: \n";
output('rgb', $images);
echo "\n\nyor: \n";
output('yor', $images);
echo "\n\nxxy: \n";
output('xxy', $images);
rgb:
<img src="red.png"><img src="green.png"><img src="blue.png">
yor:
<img src="yellow.png"><img src="orange.png"><img src="red.png">
xxy:
<img src="yellow.png">
Upvotes: 2
Reputation: 45490
Try this approach:
for( $i = 0; $i <= strlen( $cell1 ); $i++ ) {
$char = substr( $cell1, $i, 1 );
switch ($char) {
case "r":
echo '<img src="red.gif">';
break;
case "o":
echo '<img src="orange.gif">';
break;
case "g":
echo '<img src="green.gif">';
break;
default:
break;
}
}
Upvotes: 1