in the code below i have a bug (maybe more than one). i was wondering if anyone could help. i have the output below

thank you 🙂

Word provided by the user is:
Hello world
converted to lower case: hello world
hello world
string passed to translate() is: hello world
Array ( [0] => hello [1] => world ) explode() passed function
value: hello

Warning: implode() [function.implode]: Invalid arguments passed in /users/... on line 42
temp string is :

ay
y
value: world

Warning: implode() [function.implode]: Invalid arguments passed in /users/... on line 42
temp string is :

ay
y

The translated word/sentence into Pig Latin is: y

<?php
echo "Word provided by the user is: ".$_POST['word']."<br>";

$sentence = $_POST['word'];

$sentence = "Hello world";
echo $sentence."<br>";

$sentence = strtolower($sentence);


echo "converted to lower case: ".$sentence."<br>";

$cleaned_sentence = clean_string($sentence);

echo $cleaned_sentence."<br>";

$translated = translate($cleaned_sentence);

echo "The translated word/sentence into Pig Latin is: ".$translated."<br>";

function clean_string($sentence_to_be_cleaned) {
   $bad_characters = "[^a-zA-Z]";
   $new_sentence = ereg_replace($bad_characters, " ", $sentence_to_be_cleaned);
   return $new_sentence;
}

function translate($string_to_translate)
{
    // separating a sentence passed into individual words to translate into Pig Latin
    echo "string passed to translate() is: ".$string_to_translate."<br>";
	$word =  explode(' ', $string_to_translate);
    print_r ($word);
	echo "explode() passed function <br>";

// this regex will be used to check if the first letter is vowel or not
$reg_expression = '(a|e|i|o|u)';

foreach($word as $key=>$value)
{
     echo "value: ".$value."<br>";
     $temp_str = implode('',$value);
     echo "temp string is : ".$temp_str."<br>";
	 //if 1st letter of a word is a vowel
     if(check_regex($reg_expression, substr($temp_str,0,1)) == TRUE)
     {
        echo $word[i].'`yay';           
     }
     // else - 1st letter is a consonant
     else
     {
		$consonant = substr($temp_str,0,1);
		echo $consonant."<br>";
		$new_word = $temp_str.$consonant."ay";
		echo $new_word."<br>";
		$new_word = substr_replace($new_word, "", 0, 1);
		echo $new_word."<br>";
     }  
}
return $new_word;
}

function check_regex($myregex, $mystring) {
   if (ereg($myregex, $mystring)) {
      return TRUE;
   }
   else {
      return FALSE;
   }
}
?>

    Hi,

    The $word array in the translate() function is not a hash, which is how you're referring to it in the foreach loop.

    Just use ...

    foreach($word as $value){
    //...
    }

    P.

      13 days later
      Write a Reply...