Ok what I would like to do is somewhat unique, and I can’t find anything online to guide me, so hopefully I do a good job explaining it.
PROBLEM:
I have a series of if statements in PHP. To simplify, each if statement looks like this:
if($product_name == 'shoe') {
$shoe_description = '<p>Shoe description</p>';
echo $shoe_description;
}
else if($product_name == 'car') {
$car_description = '<p>Car description</p>';
echo $car_description;
}
else if($product_name == 'bottle') {
$bottle_description = '<p>Bottle description</p>';
echo $bottle_description;
}
This works fine as long as $product_name is defined as one of my variables. What I would like to do is, as the last statement, say that “if product_name matches none of my variables, show a random description from above“; so I’ll add a final else statement to the end of the above code (example – not working code):
else {
// Show one of the echo strings from above (i.e. $car_description)
//but pick randomly
}
QUESTION:
What code would I need to edit/add so that the final else statement picks one of the 3 description variables so that I can then echo it on the page?
This is a pretty basic rewrite of the logic you gave. You can usually rewrite a series of if statements into simpler logic, or into a switch statement—depending on what you’re trying to accomplish. In this case, I’d check if the
$product_namehas a description and otherwise just pick a random key.