I store the number 1 2 3 4
as the answer to multiple choice questions in MySQL database,
But I want to display them in a b c d
on web page.
I'm using PHP, how can I transform the numbers to letters using PHP?
echo "
<h2>question</h2>
<p>".$row[0]."</p>
<h2>answer</h2>
<p>".$row[1]."</p>";
The row[1]
is {1,2,3,4}
now, I want it turn to {A,B,C,D}
.
Can any one please have a look and tell me how to do it?
It is very easy:
<?php
$row = array(1, 2, 3, 4);
echo "
<h2>question</h2>
<p>".chr(64 + $row[0])."</p>
<h2>answer</h2>
<p>".chr(64 + $row[1])."</p>";
Test it: http://3v4l.org/uojsK
Create the alphabet array and use the numbers to get the right letter by index (num-1)
$letters = range('a','z');
$num = 3;
var_dump($letters[$num-1]);//"c"
i.e.
$letters = range('a','z');
echo "
<h2>question</h2>
<p>".$letters[$row[0]-1]."</p>
<h2>answer</h2>
<p>".$letters[$row[1]-1]."</p>";
you can define an array first:
$letters = array_combine(range(1,26), range('a', 'z'));
//now just use:
echo $letters[$row[1]];
<?php
/// the $row is the array you can get from db
$row = array(1,2,3,4,5);
// Here you can add your option up-to z
$alpha = range('A','E');
$i = 0;
/// Instead of foreach loop you can run while loop
foreach($row as $rows){
echo $alpha[($row[$i]-1)].'<br/>';
$i++;
}
?>