1

I've written a class that looks at different parts of an email message. One function is to determine if each part is a file, by checking if a file name is present in its array of properties.

My check looks like:

if (array_key_exists("filename",$body_part->d_parameters)) {
  // do stuff
}

But I keep getting this error in my logs because in cases where the part is not a file (header, body etc.) there is no array key called "filename."

PHP Notice:  Undefined property: stdClass::$d_parameters in mail.php
PHP Warning:  array_key_exists() expects parameter 2 to be array, null given in mail.php
0

1 Answer 1

1

The first error is because $body_part->d_parameters doesn't exist when you reference it.

The second error is because $body_part->d_parameters isn't an array when you pass it to array_key_exists()

Solution: use isset() and is_array() before attempting to pass the object property into the function.

if ( isset($body_part->d_parameters) and is_array($body_part->d_parameters) and array_key_exists("filename",$body_part->d_parameters)) {
  // do stuff
}
Sign up to request clarification or add additional context in comments.

4 Comments

I did add a bit more text a minute later, but maybe its because I answered a relatively basic PHP question?
No worries, I don't know too, I will upvote it though. However using empty you can write a conciser conditional statement: sandbox.onlinephpfunctions.com/code/…
I had a derp moment with this. I decided to just go with if isset($body_part->d_parameters[filename])
That's fine too! I'll use array_key_exists if there's a chance of a null value too. Also you may want to use isset($body_part->d_parameters['filename']) (added quotes) Otherwise PHP is doing a constant to string translation with a warning/notice eg "Notice: Use of undefined constant filename - assumed 'filename' in..."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.