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) Commented Dec 12, 2016 at 20:12
  • @JohnBupit Thanks :) 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. 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. 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 {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.