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?

4
  • 3
    is_array($message->number)
    – John Bupit
    Commented Dec 12, 2016 at 20:12
  • @JohnBupit Thanks :)
    – Nikk
    Commented Dec 12, 2016 at 20:16
  • 1
    There is no such thing like "JSON object". JSON is a text representation of a data structure. After decoding (using json_decode()), is_array(), is_string() or other is_*() function can be used to find its type.
    – axiac
    Commented Dec 12, 2016 at 20:46
  • @axiac By that I meant JSON decoded into an object...it's a tittle had to keep it short.
    – Nikk
    Commented Dec 12, 2016 at 20:53

1 Answer 1

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 {
    ...
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.