0

I am working on an API which receives a PHP object of $POST data. I am trying to check wether the 'smsPhoneNumber' inside customFields exists but not sure how to do this.

I am currently able to check for 'email' using:

if ( property_exists( $data, 'email' ) ) {
  return true;
}

Question: How to check if 'smsPhoneNumber' exists?

--

var_dump:

object(stdClass)[1515]
  public 'email' => string '[email protected]'
  public 'customFields' => 
    array (size=2)
      0 => 
        object(stdClass)[1512]
          public 'name' => string 'Firstname'
          public 'value' => string 'james' 
      1 => 
        object(stdClass)[1514]
          public 'name' => string 'smsPhoneNumber'
          public 'value' => string '077'
5
  • Is this json decoded data? Commented Jul 13, 2018 at 12:27
  • 1
    simplest way is do a foreach on $yourobj->customFields and check required property Commented Jul 13, 2018 at 12:28
  • Ya know, there is a second parameter in json_decode() .. look it up Commented Jul 13, 2018 at 12:40
  • 1
    @tereško, I mean, you could convert this to an array but it wouldn't change much about how you'd have to access these custom fields. Commented Jul 13, 2018 at 12:45
  • yeh it would be a bit easier if the objects in customFields were arrays, but a foreach iteration is likely your best solution regardless. Commented Jul 13, 2018 at 13:15

2 Answers 2

1

You could use an array_filter to get the custom field you want.

$phoneFields = array_filter($data->customFields, function($field) {
    return $field->name === 'smsPhoneNumber';
});

This will only return objects in the array that have a name property equal to smsPhoneNumber.

if (!count($phoneFields)) {
    // Phone not found
}

// or

if ($phone = current($phoneFields)) {
    echo "The first phone number found is " . $phone->value;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The drawback of using array_filter() to search for the subarray values is:

  • array_filter() will not stop once it finds a match; it will keep iterating even after a match is found until it reaches the end of the array.

You should use a technique that allows an early break/return.

I recommend a simple foreach() with a break.

$foundIndex = null;
foreach ($data->customFields as $index => $customFields) {
    if ($customFields->name === 'smsPhoneNumber') {
        $foundIndex = $index;
        // or $wasFound = true;
        // or $smsNumber = $customFields->value;
        break;
    }
}

This will prove to be very efficient and easy to read/maintain.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.