Last active
February 16, 2021 06:55
-
-
Save mamedshahmaliyev/2ecbf38ed0a3a00bd04f96ed695bfc4d to your computer and use it in GitHub Desktop.
Fix PHP warnings: undefined array key, property, offset etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Access keys or properties of array or object | |
* @variable array|object - array or object variable | |
* @key_list array|string - list of keys, valid inputs are: ['key1', 'key2'], 'key1', 'key1->key2->key3', etc. | |
* @default_value mixed, the default value to return if key/property does not exist | |
*/ | |
function get_key($variable, $key_list, $default_value=null) { | |
if (!isset($variable)) return $default_value; | |
if (is_string($key_list)) { | |
$multi = false; | |
foreach (['->', '=>', '.', ','] as $sep) { | |
if (strpos($key_list, $sep) !== false) { | |
$key_list = explode($sep, $key_list); | |
$multi = true; | |
break; | |
} | |
} | |
if (!$multi) $key_list = [$key_list]; | |
} | |
$curr = $variable; | |
foreach($key_list as $key) { | |
if (is_object($curr)) $curr = $curr->$key ?? null; | |
else if (is_array($curr)) $curr = $curr[$key] ?? null; | |
else return $default_value; | |
if (is_null($curr)) return $default_value; | |
} | |
return $curr; | |
} | |
// usage examples | |
class Foo { | |
public $prop1 = 'prop1_val'; | |
public $prop2 = ['key' => 'val']; | |
public $prop3 = []; | |
} | |
$cls = new Foo(); | |
$cls->prop3 = ['cls' => new Foo()]; | |
$arr1 = ['key1' => 'val1']; | |
echo get_key($arr1, 'key1').'<br>'; | |
echo get_key($cls, ['prop3', 'cls', 'prop2', 'key']).'<br>'; | |
echo get_key($cls, 'prop3->cls->prop2->key').'<br>'; | |
echo get_key($cls, 'prop5->key1', 'default_val').'<br>'; | |
/** | |
Output: | |
val1 | |
val | |
val | |
default_val | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment