I want to check the key for existence in the $ arr array using the ternary operator. And if true , then display this key.

<?php $arr = array("test" => 1, "some" => 2); echo "test" ? array_key_exists("test", $arr) : echo "такого ключа нет"; ?> 

But it gives an error when writing. But where is the mistake?

  • two times echo? error must be specified. - Jean-Claude
  • one
    usually write echo array_key_exists("test", $arr) ? 'ключ есть' : 'ключа нет'; echo array_key_exists("test", $arr) ? 'ключ есть' : 'ключа нет'; - Jean-Claude
  • and how to make the 'key have' instead of the name of this key? Well, just do not write directly "test". - Beginner
  • you can’t do it in any way, you take it somewhere before checking it, so you can insert a 'key in' inside - Jean-Claude

1 answer 1

Incorrectly root construction. Logically, it should look like this:

 echo (что-то); 

The brackets are optional, but it will be clearer for you. Now insert the ternary operator array_key_exists("test", $arr) ? 'ключ есть' : 'ключа нет' inside the parentheses array_key_exists("test", $arr) ? 'ключ есть' : 'ключа нет' array_key_exists("test", $arr) ? 'ключ есть' : 'ключа нет' which literally means true ? действие_для_true : действие_иначе; true ? действие_для_true : действие_иначе;

It turns out, we remove the brackets at the same time:

 echo array_key_exists("test", $arr) ? 'ключ есть' : 'ключа нет'; 

Working Example: http://ideone.com/H68pwa

With the output of the key from the variable total:

 $arr = array("test" => 1, "some" => 2); $key = 'test'; echo array_key_exists($key, $arr) ? "ключ $key есть" : 'ключа нет'; 
  • and how to make the 'key have' instead of the name of this key? Well, just do not write directly "test". - Beginner
  • @Sven updated example - Jean-Claude
  • Yes, of course, thanks. - Beginner