there is an array of four elements

$arr = array('1name','4aaaaa','5smthn','3else'); 

It is necessary, using the minimum possible (this is important) number of operators, to go through the array, and if an element starts by one, output a message, if four, then the element itself, if not by one, not four, and not three, then output some other message

the main point of the task is to use at least any if and == using substr() is also undesirable

  • and if it starts 5 or 2? - teran
  • the array exists exactly in the form in which it is now, respectively, there will not be a two, and the five is simply ignored, because in terms of its not - inDee

2 answers 2

using at least any if and == using substr () is also undesirable

Somehow so what?

 $arr = array('1name','4aaaaa','5smthn','3else'); foreach($arr as $v){ switch ((int)($v)) { case 1: echo "сообщение"; break; case 4: echo $v; break; case 5: break; default: echo "smth else"; } } 
  • but then the case with default will work on 5 too, and will output smth else twice? - inDee
  • @inDee why? 5: break; is written 5: break; . although the logic here is not particularly clear to me, with such success it was possible to do case 3 -> smthn else , since you have a fixed value set - teran
  • smth else needs to be output just if the first is not a triple, not a unit, and not a quadruple, while it is impossible to simply make case 5 as the one number remaining, this is the problem - inDee
  • 2
    it is not so written in me, on the contrary it is necessary case 3: break; or you have a mismatch of the question and commentary under it. - teran

And if so ?

 $arr = array('1name','4aaaaa','5smthn','3else'); $answer = array(1=>'message 1', 4=>'##', 5=>'message 2'); foreach($answer as $key=>$message){ $item = $arr[array_search($key, $arr)]; echo $item . ':' . str_replace('##', $item, $message) . PHP_EOL; } 

Returns:

 1name:message 1 4aaaaa:4aaaaa 5smthn:message 2