Jump to content

How to display an image for each number


igorek24

Recommended Posts

How can I display an image for a number? For example, if I have a number 185 that I pulle from DB, I would like to rendered as html as:

<img src="1.jpg" alt="1">
<img src="8.jpg" alt="8">
<img src="5.jpg" alt="5">

Any help would be greatly appreciated.

Link to comment
Share on other sites

1. Create/download 10 different image files for each digit.

2. Create a function to take a numeric string value and return the HTML with an image for each digit

 

The function could go something like this:

 

 

function convertToImage($numberStr)
{
    //Check that input only has numeric characters
    if(!ctype_digit()) { return false; }
 
    //Split string into an array of each character
    $numbersAry = str_split($numberStr);
 
    //Loop through each character and create HTML for image
    $output = "";
    foreach($numbersAry as $number)
    {
        $output .= "<img src='1.jpg' alt='1'>";
    }
 
    //Return results
    return $output;
}
Link to comment
Share on other sites

So - you have a value. You want to create another consistent value from it? Assuming that they are all going to be jpg files and that they are all in the current folder then don't you just want to do this:

 

Assuming that your query produced $results containing a field named 'number':

$output_html = '';
while ($row = $results->fetch())
{
$srcname = $row['number'] . '.jpg';
$alt = $row['number'];
$output_html .= "<img src='$srcname' alt='$alt'>";

 

Now echo out $output_html where you want it.

 

I'll let you fit this into your scheme.

Link to comment
Share on other sites

Here is the result:

public function odometer($carID)
    {
        $mileage = str_split($this->pullMileageLastRecord($carID));
        $output = "";
        foreach ($mileage as $mile)
        {
            $output .= "<img src='img/speedo-numbers/$mile.gif' alt='$mile'>";
        }
        return $output;
    }

img2.png

Link to comment
Share on other sites

@ginerjm, the OP will not have an image for every possible number value. E.g. there will be no "525.jpg" for the number 525. So, the correct process is to iterate over each character in the numeric string.

 

@Jacques1, you are correct. That approach removes the necessity for splitting the string into an actual array. It's never seemed logical to me to reference characters in a string as if it was an array, so that did not come to mind when providing a solution.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.