ultraloveninja
ultraloveninja

Reputation: 2139

Combine two PHP variables into one if one variable is not empty

So this is a zany thing that I'm attempting to do, but what I am trying to achieve is querying out some info in WordPress with categories. If a post comes back with a parent category, then echo that out with the child category with a | seperator. If no parent category then just echo out the category.

Here's what I'm trying so far:

<?php
$categories = get_the_category();
$catName = $categories[0]->name;
$catParent = get_cat_name($categories[0]->category_parent);

        if($catParent) {
            $fullCat = $catParent '|' $catName;
        } else {
            $fullCat = $catName;

echo $fullCat;
?>

I know this is incorrect, but basically, I'm trying to wrap my head around how to accomplish this. I'm not sure how to combine two variables to use one and then add the separator within the two.

Was also wondering if maybe a ternary operator might be better here too? That was more of thought than anything and probably not that necessary to make this work correctly.

Upvotes: 1

Views: 237

Answers (3)

andy
andy

Reputation: 46

You're wanting to check if $catParent is empty so you can use the empty() function to do that check for you. Quick edit...you need periods (.) in between things you are concatenating.

Link to the docs.

    if(empty($catParent)) {
        $fullCat = $catParent . '|' . $catName;
    } else {
        $fullCat = $catName;
    }

Upvotes: 2

srimaln91
srimaln91

Reputation: 1326

You can use . (Concatenation) operator to achieve this. Look at the code below.

<?php
$categories = get_the_category();
$catName = $categories[0]->name;
$catParent = get_cat_name($categories[0]->category_parent);

        if($catParent) {
            $fullCat = $catParent . '|' . $catName;
        } else {
            $fullCat = $catName;

echo $fullCat;
?>

Upvotes: 0

Bundhoo Nadeem M.
Bundhoo Nadeem M.

Reputation: 75

You must use '.' to concat.

Example:

$fullCat = $catParent. ' | '. $catName;

Upvotes: 0

Related Questions