HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Checking for existing key in multi-dimensional array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
multiarraycheckingdimensionalforexistingkey

Problem

Say I have a data structure like this:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(3) "foo"
  ["message"]=>
  array(1) {
    ["action"]=>
    string(3) "PUT"
  }
}


Where 'message' and 'action' are both optional. To check if they're present my first attempt would be to write something like this:

if (array_key_exists('message', $array) && array_key_exists('action', $array['message'])){
}


Is there a cleaner implementation?

Solution

You can just do this!

if (isset($array["message"]["action"])) { /*...*/ }


Proof:

 1,
    "name" => "foo",
    "message" => [
        "action" => "PUT",
    ],
];

var_dump(isset($array["message"]["action"])); // true

$array = [
    "id" => 1,
    "name" => "foo"
];

var_dump(isset($array["message"]["action"])); // false


No log entries.

Do note that if your value is null, then isset will also return false. You probably shouldn't be creating values with null.

Code Snippets

if (isset($array["message"]["action"])) { /*...*/ }
<?php

error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);

$array = [
    "id" => 1,
    "name" => "foo",
    "message" => [
        "action" => "PUT",
    ],
];

var_dump(isset($array["message"]["action"])); // true


$array = [
    "id" => 1,
    "name" => "foo"
];

var_dump(isset($array["message"]["action"])); // false

Context

StackExchange Code Review Q#23991, answer score: 3

Revisions (0)

No revisions yet.