there is an array $arr = array('1a','2b','4c','5d','3g'); and there is an array check for the initial character of each element

 foreach ($arr as $element){ if (substr($element, 0, 1) == 1) echo "one"; elseif (substr($element, 0, 1) == 2) echo " two "; elseif (substr($element, 0, 1) == 4) echo $element; elseif (substr($element, 0, 1) != 3 && substr($element, 0, 1) != 1 && substr($element, 0, 1) != 2) echo " not one, two or three"; } 

you need to simplify by replacing if and == with a ternary operator help plz, I break my head for a long time

  • Are you not confused by the call to the code substr($element, 0, 1) written 6 times? - teran
  • and switch no longer in fashion? - Manitikyl

1 answer 1

 foreach ($arr as $element){ $first = substr($element, 0, 1); $toEcho = ($first == 1)? "one" : ( ($first == 2)? "two" : ( ($first == 4)? $element : ( ($first != 3)? "not one, two or three" : "" ) ) ); if (!empty($toEcho)) echo $toEcho; } 
  • $toEcho != "" can be replaced by !empty($toEcho) - Let's say Pie