phparraysarray-key-exists

If array key exists return its value


I have an array called all_teams which contains the following

Array
(
    [33448] => Team1
    [33466] => Team2
    [33467] => Team3
    [33476] => Team4
    [33495] => Team5
)

I do a check within a foreach to check if teamId is in the array keys. If the array key exists I want to display the key's value.

So far I have

if(array_key_exists(intval($team['teamId']), $all_teams)) {
   echo 'set';
   // array key value needs to be here
} else {
   echo 'not set';
}

Solution

  • As per my comment, you simply want to access an array element's value by its index. It is as straightforward as doing $all_teams[<<index>>], which is in this case the parsed teamId:

    $teamId = intval($team['teamId']);
    if(array_key_exists($teamId, $all_teams)) {
       echo $all_teams[$teamId];
    } else {
       echo 'not set';
    }