Search code examples
phparraysindexingtextinput

PHP: If String[Index] is in Array, PHP: String from String[1] to String[last]


Is there a PHP call for in_str?

…something similar to in_array..

Am using an if-else to take the each word (string) in the array of strings (from a form-input-text) to see if the start index [0] is equal to a single character string in another array..

Also, how does one get at a string from string[1] to string[last]?

(these two questions are highlighted in the code using the format: **code**)

      if(isset($_POST['RadioButtonName']) &&
      $_POST['RadioButtonName'] == 'aValue') {
        $stringsArray = array($_POST['FormInputText']);
        $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");

        foreach ($stringsArray as $stringsArrayString)
          {
            if (**in_str**($stringsArrayString[0], $vowels)) {
              echo $stringsArrayString . "aWord" . "<&nbsp;>";
            }
            else {
              echo "**$stringsArrayString[1] to $stringsArrayString[last]**" . "$stringsArrayString[0]" . "aWord" . "<&nbsp;>";
            }
          }
      }

Solution

  • you can use strpos to check if a letter is in a string, but to search an array you'll need to use a foreach...

        foreach($vowels as $vowel)
        {
            $firstLetterIsAVowel = (strpos($stringsArrayString, $vowel) === 0 ? true : false);
        }
    
            if ($firstLetterIsAVowel)) {
              echo $stringsArrayString . "aWord" . "<&nbsp;>";
            }
            else {
              echo "**".substr($stringsArrayString, 1) . "$stringsArrayString[0]" . "aWord" . "<&nbsp;>";
            }
    

    note the use of === instead of == as strpos returns false if not found, and 0 == false. I did it like that because that was your question, but i'd rather check if $stringArrayString[0] is a vowel like this...

        in_array ( $stringArrayString[0] , $vowels)