0

When I have an input like below...

{  
     "number":[  
        "+39XXXXXXXX",
        "+34XXXXXXXX",
        "+49XXXXXXXX"
     ],
     "message":"Sample msg..."
}

I handle it with a foreach loop—like so:

foreach ($message->number as $key => $number) {
    ...                                     
}

However when I have an input like this:

{  
     "number": "+49XXXXXXXX",
     "message": "Sample msg..."
}

I receive an error, cause there is no array to be looped inside the object.

So what is a good and efficient way to detect for this?

Nikk
  • 7,384
  • 8
  • 44
  • 90
  • 3
    [`is_array($message->number)`](http://php.net/manual/en/function.is-array.php) – John Bupit Dec 12 '16 at 20:12
  • @JohnBupit Thanks :) – Nikk Dec 12 '16 at 20:16
  • 1
    There is no such thing like "JSON object". [JSON](https://en.wikipedia.org/wiki/JSON) is a text representation of a data structure. After decoding (using [`json_decode()`](http://php.net/manual/en/function.json-decode.php)), [`is_array()`](http://php.net/manual/en/function.is-array.php), [`is_string()`](http://php.net/manual/en/function.is-string.php) or other [`is_*()` function](http://php.net/manual/en/ref.var.php) can be used to find its type. – axiac Dec 12 '16 at 20:46
  • @axiac By that I meant `JSON` decoded into an object...it's a tittle had to keep it short. – Nikk Dec 12 '16 at 20:53

1 Answers1

2

You can check if the var value is array using the is_array function:

if (is_array($message->number) {
    foreach ($message->number as $key => $number) {
        ...                                     
    }
} else {
    ...
}
rogeriolino
  • 1,095
  • 11
  • 21