Skip to content

Instantly share code, notes, and snippets.

@TakesTheBiscuit
Created February 12, 2018 15:10
Show Gist options
  • Save TakesTheBiscuit/f58034781e004b24d144ecaa41b4af69 to your computer and use it in GitHub Desktop.
Save TakesTheBiscuit/f58034781e004b24d144ecaa41b4af69 to your computer and use it in GitHub Desktop.
PHP property exists check
<?php
$str = json_encode(['test'=>true]);
$obj = json_decode($str);
var_dump($obj);
echo PHP_EOL.'<br>';
$keys = [
'tests',
'testies',
'test'
];
foreach ($keys as $key) {
if (property_exists($obj, $key)) {
echo 'got '.$key;
} else {
echo $key. ' was not found';
}
echo PHP_EOL.'<br>';
}
?>
@TakesTheBiscuit
Copy link
Author

And showing the values of an object through dynamic variable selection:

<?php

$str = json_encode(['test'=>true, 'pig'=>'headed']);
$obj = json_decode($str);

var_dump($obj);
echo PHP_EOL.'<br>';

$keys = [
    'tests',
    'testies',
    'test',
    'pig'
];

foreach ($keys as $key) {
    if (property_exists($obj, $key)) {
        echo 'got '.$key;
        echo ' | value demo:'.$obj->$key;
    } else {
        echo $key. ' was not found';
    }
    echo PHP_EOL.'<br>';
}
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment