-2

What's the easiest way to echo $result->data['id'] that won't throw an error?

$result = someBackendCall(1, 2, 3);
if($result && isset($result->data) && isset($result->data['id'])){
    echo $result->data['id'];
}
jozenbasin
  • 2,142
  • 2
  • 14
  • 22
  • 1
    Easiest? They are all as easy as it is to type them. Do you mean, most efficient, less overhead, cleanest code maybe? – IncredibleHat Oct 16 '17 at 01:17
  • Literally the least amount of typing to get the job done. – jozenbasin Oct 16 '17 at 01:19
  • 2
    Possible duplicate of [Best way to test for a variable's existence in PHP; isset() is clearly broken](https://stackoverflow.com/questions/418066/best-way-to-test-for-a-variables-existence-in-php-isset-is-clearly-broken) – LF00 Oct 16 '17 at 01:48

2 Answers2

2

Its sort of subjective, as there are various ways, and some people find one way easier than another. What you wrote can even be considered easiest by some.

Also, for example, you could just do:

echo (isset($result->data['id'])?$result->data['id']:'');

Or, you could put it in a standard if block:

if (isset($result->data['id'])) { echo $result->data['id']; }

Another way, would be to make a tiny little helper function that floats about that you reuse:

function echoVar(&$input=null) { if (isset($input)) { echo $input; } }

echoVar($result->data['id']);
echoVar($result->data['name']);

I've not really used the mini function method, so I cannot say for sure if its really any easier, since it really obscures your code reading it later.

One thing to note is, isset can take the full nested variable, and it checks in step. You do not need to clal three issets in a row on each level of your intended value.

IncredibleHat
  • 4,000
  • 4
  • 15
  • 27
1
if (!empty($result->data['id'])) {
echo $result->data['id'];
}
miknik
  • 5,748
  • 1
  • 10
  • 26
  • What if his value is set, but it is empty (or zero) intentionally? Using 'empty()' will not work as well. – IncredibleHat Oct 16 '17 at 01:30
  • If its empty he can't echo it. I took a chance on the fact that his data id number wouldnt be zero – miknik Oct 16 '17 at 01:33
  • Right, I would as well think an ID should never be empty (hopefully!). But if he was going to use the 'shorthand' for all manner of things, it may trip him up down the road when a zero, is wanting to be output. – IncredibleHat Oct 16 '17 at 01:35
  • 1
    Yeah for sure, but his main criteria was minimum typing, so this can't be important, right? – miknik Oct 16 '17 at 01:36