Join my Laravel for REST API's course on Udemy 👀

PHP: How to check whether a key exists in an array

July 19, 2022  ‐ 1 min read

Wonder how you to check whether a key exists in an array? You can say what you want about PHP but this is one clear function name: array_key_exists().

<?php

$arr = ['key' => 'value'];

if (array_key_exists('key', $arr)) {
  echo 'No need to worry about "Undefined array key" errors';
}

Note: if you wish to access an array value by its key in an assignment operation you can use the null coalescing operator.