patternphpMinor
Checking for existing key in multi-dimensional array
Viewed 0 times
multiarraycheckingdimensionalforexistingkey
Problem
Say I have a data structure like this:
Where 'message' and 'action' are both optional. To check if they're present my first attempt would be to write something like this:
Is there a cleaner implementation?
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!
Proof:
No log entries.
Do note that if your value is
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"])); // falseNo 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"])); // falseContext
StackExchange Code Review Q#23991, answer score: 3
Revisions (0)
No revisions yet.