I’m working on a shortcode to display a custom post type, which mostly works. I don’t control the feed this data is coming from, hence the need to split up the title based on delimiters. The problem I’m experiencing is that the variables first, second, third, and fourth can be null, and I don’t know how to account for this in this context.
function display_custom_post_type() {
// ... irrelevant code ...
$title = (get_the_title ());
$str = preg_split('(||[|]|=)', $title,-1, PREG_SPLIT_NO_EMPTY);
print_r($title);
$first = $str[0];
$second = $str[1];
$third = $str[2];
$fourth = $str[3];
$string .= '<h3 class="test-parl-title"><div>' . $first . '</div></h3>';
$string .= '<h5>' . $second . ' ' . $third . ' ' . $fourth . '</h5>';
// ... irrelevant code ...
return $string;
}
5
Answers
you can check if value that come from html is empty string and make for loop to transfer empty string to null
you can you also
isset($var);
also to check if variable have null value or undefine variable.UPDATE:
In a comment you said that $str[0] is always populated and the others vars can be null:
I used $str[0] in h3. I deleted it and imploded whatever remained if it wasn’t empty. This is shorter than using $first, $second, $third, $fourth, etc.
Try some syntactic sugar
If you are running php 7.0.x or higher you can use the null coalescing operator. It’s syntatic sugar but it’s very easy to read:
The variables are getting assigned the $str[0] if it exists and is not null, otherwise they are assigned the second argument (here, an empty string, but you can use what you want).
Here’s your whole function rewritten in a slightly easier to read format (untested):
You can try use
empty
function:More detail is here. Hope help you.
Why not easily with standard PHP functions?