How to definte variables for fields without data in them?

15
March 16, 2019, at 00:40 AM

I've got a number of calls to data in a WordPress site using a number of custom fields. The fields aren't required to fill out on the back end. So in my templates, I have calls like this:

<?php if( $additional_fields[ 'Time' ] ) { echo 'Duration: ' . $additional_fields[ 'Time' ] . '<br>'; } ?>

Now this does work. Which is great. But if I turn on WP Debug, and there's no data for this field, I get greeted by the following:

Notice: Undefined index: Time in /home/hellod8/public_html/wp-content/themes/my-theme/page-data.php on line 63

Now again, not mission critical. If I turn debugging off, the problem goes away. However, I'd still like to solve this.

I thought I could do this above the call to the function:

<?php $additional_fields[ 'Time' ] = ''; ?>

But all that does is not display anything at all for that field.

So what would work to eliminate the error?

Answer 1

You an use isset() to determine if the variable is set. Example:

if( isset($additional_fields['Time']) ){
    echo $additional_fields['Time'];
}

If you're looking to see if the variable is set and not empty, you can use empty(). Example:

if( !empty($additional_fields['Time']) ){
    echo $additional_fields['Time'];
}

empty() will check for a myriad of things like whether the variable isset, or the value is blank, zero, false, or null. empty() is slightly slower than isset() (primarly because of these additional checks).

Empty would be the same as saying:

if( isset($additional_fields['Time']) && $additional_fields['Time'] ){
    echo $additional_fields['Time'];
}

isset() - http://php.net/manual/en/function.isset.php

empty() - http://php.net/manual/en/function.empty.php

READ ALSO
laravel join 4 tables

laravel join 4 tables

I started to learn the Laravel 58 framework and got a problem

36
Multiple search from the database [duplicate]

Multiple search from the database [duplicate]

This question already has an answer here:

44
in laravel 5.8 is its possible to spoof the url bar whit out reloading the page

in laravel 5.8 is its possible to spoof the url bar whit out reloading the page

Is it possible in laravel to spoof an url whit out reloading the page, for example when you have an url like this webpage/post/1 and 1 standing for the id, that you then can make it webpage/post/{Post-Name} whit out using webpage/post/#{Post-Name} whitout...

19
How to set up routing for a php api script create.php?

How to set up routing for a php api script create.php?

I'm trying to setup an url in my laravel project from which my database can receive post requests, i have this script i made in php and i put in /public folder, it works fine when hosted in xampp but when i put it in my laravel project i get a not found error this is what my php script...

22