There are 2 arrays:

$a1 = array('country' => array('Russia', 'Ukraine', 'Belarus')); $a2 = array('country' => array('Russia' => 'Krasnodar', 'Ukraine' => 'Kiew', 'Belarus' => 'Minsk')); 

The task is to check that the value has a key, not an index. The second array is correct, the first is not. Is there such a possibility or dig somewhere in the other direction?

UPD: Helped option from comments with is_string check.

3 answers 3

Use the array_key_exists or isset function

 if (array_key_exists('key', data)) echo 'Exists'; if (isset(data['key'])) echo 'Exists'; 

Just be careful, if the key is present but is NULL , then array_key_exists will return true , and isset will return false

  • Unfortunately, the check gives the wrong result. - Dmitry Goncharov
  • I in foreach do check for the presence of a value in a key. $ array = array ('country' => array ('Russia', 'Ukraine', 'Belarus')); foreach ($ array as $ key => $ array) {if (isset ($ array [$ key]) {echo 'yes';} else {echo 'no';}} returns yes, and I only need yes if the array is of the second type from the header. I ask the petition that the code is not executed, I am writing from the phone. - Dmitry Goncharov
  • @DmitryGoncharov It makes no sense to check isset($array[$key]) inside foreach . Because the cycle initially runs only on the existing elements. In this case, your $key will be 0, 1, 2 ... - Anton Shchyrov
  • @DmitryGoncharov Can you use the is_string($key) check? - Anton Shchyrov
  • here, and I need the key to be just the value that I asked. Without assigning indexes and thereby passing the test. It is necessary that either, as I asked array ('first' => 1, 'second' => 2), but not array ('first', 'second') or output echo 'no'; Is it possible? - Dmitry Goncharov

Alternatively, use array_key_exists :

 if (array_key_exists('Russia', $a1['country'])) { echo 'Россия ΠΈΠΌΠ΅Π΅Ρ‚ значСния`; } else echo 'Россия Π½Π΅ ΠΈΠΌΠ΅Π΅Ρ‚ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠΉ`; 

    It is necessary to check whether the array is associative:

     $keys = array_keys($array); $is_assoc = array_keys($keys) !== $keys;