I have a form where I will enter one of three words that I have placed in an array, chose a category and when I press send I want another word from another array to show up, the word that shows up should have the same key as the word entered in the form.
This is what I've tried so far, after searching for a while.
function wordswap() {
$word=array('hello','happy','yes');
$opp=array('bye','sad','no');
for($y=0;$y<=2;$y++){
if($text==$word[$y]){ //$text is the word entered in the form
echo "$opp[$y]";
}
}
}
When enter "hello" into the form and press send, I want "bye" to show up etc. Any help would be much appreciated!
I think the problem is that you're echo
ing a string - if you remove the double quotes around $opp[$y]
then it should work :)
function wordswap() {
$word=array('hello','happy','yes');
$opp=array('bye','sad','no');
for($y=0;$y<=2;$y++){
if($text==$word[$y]){ //$text is the word entered in the form
echo $opp[$y];
}
}
}
Just use a mapping instead of two arrays here:
function wordswap($text) {
$wordMap = [
'hello' => 'bye',
'happy' => 'sad',
'yes' => 'no',
];
return empty($wordMap[$text]) ? null : $wordMap[$text];
}
You don't need to write your own function. You can do it with only one from standard lib: str_replace(array('hello','happy','yes'), array('bye','sad','no'), $text);
Here you have demo: https://eval.in/137815
Someone posted the correct solution, but it looks like it got removed. Here it is: (link: https://eval.in/137813)
function wordswap($input) {
$word=array('hello','happy','yes');
$opp=array('bye','sad','no');
$key = array_search($input, $word);
if (isset($opp[$key])) {
return $opp[$key];
}
return FALSE;
}
echo wordswap('hello');