...

View Full Version : Resolved Text-numbers to images



[vengeance]
11-06-2010, 12:19 AM
Hello.

I have a script that counts how many users that exist in the system. Instead of printing it as text, I'd like to show them as images. I have the numbers 0 to 9 in .png files.

What would be the easiest way to split up "132" and make three different <img> tags for each individual number?


<img src="1.png" /><img src="3.png" /><img src="2.png" />

Thanks

Keleth
11-06-2010, 12:38 AM
You mean, if you got 132 in a variable, how to break it up?

Convert it to a string and treat it like an array:



$count = 132;
$count = (string) 132;

foreach ($count as $number) {
echo "<img src=\"{$number}.png\">";
}

[vengeance]
11-06-2010, 12:45 AM
You mean, if you got 132 in a variable, how to break it up?

Convert it to a string and treat it like an array:



$count = 132;
$count = (string) 132;

foreach ($count as $number) {
echo "<img src=\"{$number}.png\">";
}

Do you mind explaining deeper what you're doing there?

Also, it gives me the following:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\project\index.php on line 86

Inigoesdr
11-06-2010, 12:56 AM
Here, try this:

$numbersArray = str_split((string) $count);
foreach($numbersArray as $num)
{
echo '<img src="' . $num . '.png" />';
}
It's splitting the count into an array of the individual numbers, then looping through them and printing out an image tag for each one.


Could also do it this way:

$count = 132;
$count = (string) $count;
$countLen = strlen($count);
for($i = 0; $i < $countLen; $i++)
{
echo '<img src="' . $count[$i] . '.png" />';
}

Keleth
11-06-2010, 12:59 AM
I fail at testing! I did a small quick check and didn't bother to actually test the code I gave you.

Quick fix, though more complicated!


$count = 132;
preg_match_all('/\d/', $count, $matches);


$matches[0] will contain your results.

Before what I was doing was typecasting $count (your number) as a string. If you echo $stringName[3] (randomly location in a string), it'll echo out the character in that position. I thought, hey, we can do that with foreach! But foreach doesn't like strings, so we go to instead, for!


$count = 132;
$count = (string) $count;

for ($position = 0; $position < strlen($count); $position++) {
echo "<img src=\"{$count[$position]}.png\">";
}


I do like regex better through :p

Edit: Also, Inigoesdr is smarter then me :D

[vengeance]
11-06-2010, 01:06 AM
Thanks both of you. Was exactly what I was looking for.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum