endymion1818
endymion1818

Reputation: 485

php variable change result

I have a field called into my php template which is a list of product categories. It's actually either a number 1, 2 or 3.

At the moment I have echoed that number into my template like this:

<p>< php the_field('category'); ></p>

What I would like to do is change that category when it is printed.

For example, if the category is 1, I would like it to read "first category", if the category is 2, "second category" etc.

Is this possible with PHP?

Thanks in advance for your assistance.

Upvotes: 2

Views: 128

Answers (3)

user3744194
user3744194

Reputation: 46

There are a lot of options which you can use for this issue, for example you can use switch-case for output this data, but you should write a lot of code in this case. Second option use if-elseif statement, it is not good solution for this problem. The better solution are using ductionary array with you shortcuts, for example: $dictinary = array (1 => 'first category', 2 => 'Second catecory'); echo $dictionary[$categoruId];

But best solution is using special lingual library which decide this problem.

Upvotes: 2

michal.hubczyk
michal.hubczyk

Reputation: 697

You can also predefine associative array like:

$categories = array();
$categories[1] = "First";
$categories[2] = "Second";
$categories[3] = "Third";

and in code just call

echo $categories[$category]

where $category is your category number;

Upvotes: 1

Michael O&#39;Brien
Michael O&#39;Brien

Reputation: 401

You can accomplish this using a switch statement.

switch($category)
{
    case 1:
        echo "First Category";
    break;
    case 2:
        echo "Second Category";
    break;
    case 3:
        echo "Third Category";
    break;
    default:
        echo "";
    break;
}

Upvotes: 1

Related Questions