I am trying to write a program in php which first prompts a user for a string. once they enter a string it is supposed to give the equivalent digits if it were on a phone. eg ABC(2)
, DEF(3)
, GHI(4)
, JKL(5)
, MNO(6)
, PQRS(7)
, TUV(8)
, WXYZ(9)
. Im using a for loop and nested if statements but i am not getting the correct output. Am I going about this the right way? my code is below
<?php
$str = $_POST['usersString'];
$len = strlen($str);
for($i=0; $i<$len-1; $i++){
if($i="a" || $i="b" || $i="c"){
echo "1";
}
if($i="d" || $i="e" || $i="f"){
echo "2";
}
if($i="g" || $i="h" || $i="i"){
echo "3";
}
}
?>
<form action="task17.php" method="POST">
Enter a string <input type="text" name="usersString" />
<input type="submit" value="enter" />
</form>
<?php
$str = $_POST['usersString'];
$len = strlen($str);
for($i=0; $i<$len; $i++){
if($str[$i]=="a" || $str[$i]=="b" || $str[$i]=="c"){
echo "1";
}else if($str[$i]=="d" || $str[$i]=="e" || $str[$i]=="f"){
echo "2";
}else if($str[$i]=="g" || $str[$i]=="h" || $str[$i]=="i"){
echo "3";
}
}
?>
your condition is wrong $i="a" It should be $str[$i]=="a"
$i
isn't going to be a letter in your loop, it's going to be an integer. What you want is to use $i
as the offset of $str
like $str[$i]
. So with 'abc' $str[0]
will be 'a'.
I would personally use an array for this to store the values:
$len = strlen($str);
$array = [ 'a' => 1, 'b' => 1, 'c' => 1, 'd' => 2, 'e' => 2, 'f' => 2 ];
// and so on...
for($i=0; $i<$len; $i++){
echo $array[ $str[$i] ];
}
Note that I also used $i<$len
rather than $i<$len-1
. I don't think you want to use less than with -1. This would lead you to exclude the last character.
Use $str[$i] instead of $i in your If conditions like
if($str[$i]=="a" || $str[$i]=="b" || $str[$i]=="c"){ echo "1"; }
change your for loop to
for($i=0; $i < $len; $i++)
{
}
$str = "ADFJ";
$digitArr = array('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz');
$strlne= strlen($str);
$digCount = count($digitArr);
for ($i = 0; $i < $strlne; $i++) {
$j = 0;
while ($j < $digCount) {
if (stripos($digitArr[$j], $str[$i]) !== false) {
$output[] = $j+1;
break;
}
$j++;
}
}
print_r($output);