i have the following array:
$keyvisual_data = array( 'video_file' => $row->field_field_video[0]['rendered']['#item']['uri'], 'bild_file' => $row->field_field_bild[0]['rendered']['#item']['uri'], 'subline_src' => $row->_field_data['nid']['entity']->field_key_titel['und'][0]['safe_value'], 'screenreader_src' => $row->field_field_alt_screenreader[0]['rendered']['#markup'], 'alt_src' => $row->field_field_bild[0]['rendered']['#item']['alt'] );
it might happen that some of the fields are not set, this is okay. in fact i am getting this PHP notice:
Notice: Undefined offset: 0 in bafa_insert_keyvisual() ...........
is it somehow possible to assign a default value to each key in case it is undefined WITHOUT checking each field of the array manually?
thanks for help
You can do an isset() : if(isset($array[0])){ echo $array[0]; } else { //some error? }
To resolve undefined index error, we make use of a function called isset() function in PHP. To ignore the undefined index error, we update the option error_reporting to ~E_NOTICE to disable the notice reporting.
It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.
The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.
No there is not
You can do an isset()
:
if(isset($array[0])){ echo $array[0]; } else { //some error? }
Or if you know that you are only going to be checking index 0:
$array = $array + array(null);
So if the original $array[0]
was unset, now it is null
Yes, add @
before the field like:
$keyvisual_data = array( 'video_file' => @$row->field_field_video[0]['rendered']['#item']['uri'], 'bild_file' => @$row->field_field_bild[0]['rendered']['#item']['uri'], 'subline_src' => @$row->_field_data['nid']['entity']->field_key_titel['und'][0]['safe_value'], 'screenreader_src' => @$row->field_field_alt_screenreader[0]['rendered']['#markup'], 'alt_src' => @$row->field_field_bild[0]['rendered']['#item']['alt'] );
and then initialize the nulls:
if($keyvisual_data['video_file'] === null) $keyvisual_data['video_file'] = $default_video_file;
etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With