Issue
I'm trying to create a morse decoder using PHP, I'm nearly done but i'm getting some fatal errors, anyone could help me out, thanks.
Fatal error: Uncaught Error: Array callback must have exactly two elements in C:\xampp\htdocs\cegep\01_introduction_programmation_web\tp2\index.php:49
Stack trace:
#0 C:\xampp\htdocs\cegep\01_introduction_programmation_web\tp2\index.php(57): decrypter('-... .-. .- ......', Array)
#1 {main} thrown in C:\xampp\htdocs\cegep\01_introduction_programmation_web\tp2\index.php on line 49
PS: It's my first time using this website so if I didn't post that right sorry, just point me my mistakes! Here's my code:
<?php
$tableau_morse = array(
".-" => "A",
"-..." => "B",
"-.-." => "C",
"-.." => "D",
"." => "E",
"..-." => "F",
"--." => "G",
"...." => "H",
".." => "I",
".---" => "J",
"-.-" => "K",
".-.." => "L",
"--" => "M",
"-." => "N",
"---" => "O",
".--." => "P",
"--.-" => "Q",
".-." => "R",
"..." => "S",
"-" => "T",
"..-" => "U",
"...-" => "V",
".--" => "W",
"-..-" => "X",
"-.--" => "Y",
"--.." => "Z",
".----" => "1",
"..---" => "2",
"...--" => "3",
"....-" => "4",
"....." => "5",
"-...." => "6",
"--..." => "7",
"---.." => "8",
"----." => "9",
"-----" => "0",
"/" => " " );
$phrase1 = "-... .-. .- ...- ---";
$phrase2 = "- --- -. / -.-. --- -.. . / ..-. --- -. -.-. - .. --- -. -. . / -... .. . -.";
function decrypter($phrase, $tableau_morse) {
$characters = explode(" ", $phrase);
$character_decryptee = "";
foreach($characters as $character) {
$character_decryptee .= $tableau_morse($character);
return $character_decryptee;
}
}
echo decrypter($phrase1, $tableau_morse);
?>
Solution
You have two problems. Firstly, your array reference in your function uses function call syntax.
$character_decryptee .= $tableau_morse($character);
should be
$character_decryptee .= $tableau_morse[$character]; // Note square brackets
Secondly, you've placed your return statement inside your foreach
loop, so only one character is decoded. Move it outside the loop.
Together, these changes give you
function decrypter($phrase, $tableau_morse) {
$characters = explode(" ", $phrase);
$character_decryptee = "";
foreach($characters as $character) {
$character_decryptee .= $tableau_morse[$character];
}
return $character_decryptee;
}
which decodes the first phrase to BRAVO
Answered By - Tangentially Perpendicular
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.