Skip to content
Advertisement

How to use a Function of Switch/Case, if at all?

I have various products inside a database, each has its own price, the pattern to output a product price is:

$product[i]["price"]

I also have various “product types”, which are manually defined in my code, each with index number that will relate to each product accordingly:

JavaScript

I want to echo a message according to the price, and to the type, for each product.

My code pattern would be something like:

JavaScript

(lorem ipsum stuff means I have some static content within the code).

Echoed line should be:

  1. If price is 0 –> <span class="free">Free</span>

  2. If price > 0 –> Echo $ sign + the price $product[i]["price"]

  3. By default/fallback –> Don’t echo anything

  4. If the type is special, no matter what the price is –> Echo It's special

Intuitively it sounds like something to handle with switch command, but I really don’t know how to use it the way I want, which probably involves a function. I only know the most basic form of switch command, I assume that my code should be something like:

JavaScript

Yes, I know it’s a complete mess, but no clue how to do this.

Edit:

For example, when $product[i]["price"]=50 and $type2="normal"

function_output($product[2]["price"],$type2) should return: $50

Edit 2:

Basically I want the function to used in a similar way to following method:

JavaScript

and then:

JavaScript

Advertisement

Answer

I’m assuming a price can never be less than zero.
So it seems that there are only three output options: “special”, “free”, or “price”.

PHP’s elseif might be more effective here:

JavaScript

But you can also use switch to evaluate multiple variables by passing it a value of true.
This might be useful if you’re going to add more options in the future.

JavaScript

Here’s a working example.


Edit

Just for fun, a short version using nested ternary operators:

JavaScript

Working Example

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement