HiGonz HiGonz - 3 months ago 9
PHP Question

Checking if value is true when names are similar in PHP

I have some columns in a table named "hasMonday", "hasTuesday", "hasWednesday", etc... with boolean values to know if a certain product belongs to a certain day (can appear at more than one day)

Now I'm making a list of days and show the data of the product if it is available (true). Something similar to this:

Monday (hasMonday=true)

Data of the product, price, etc.

Tuesday (hasTuesday=false)

There is no product for this day

--

I made an array with the days of the week and now I am trying to know it this day has a product. Here is my code so far:

$days= array("Monday", "Tuesday", "Wednesday", "Thursday","Friday","Saturday","Sunday");

foreach ($days as $day) {

echo '<div id="$day" class="dayDiv">';
echo "<h4>$day Products</h4>";
if ($Product['hasMonday'] = true) {
// Show the info
}else{
// "No info to show" message
}...


As you can see, the above code repeats all the product on each day, so I would appreciate any help to check this using the less steps possible. Something like:

foreach ($days as $day) {

echo '<div id="$day" class="dayDiv">';
echo "<h4>$day Products</h4>";
if($Product['has.$day']){
//show the info
}else{
// "No info to show" message
}


Not sure if what I wrote is possible but I believe it helps to understand a bit more what I'm trying to get.

Thanks in advance for your answers

Answer

I think you're looking for:

if ($Product["has$day"]) {

The way you suggested (if($Product['has.$day']){) was on the right track, but variables aren't parsed within single quotes, and the concatenation operator (.) is not necessary when interpolating a variable into a string like that.

As others have commented, this way won't work in cases where there is any additional string in the key after the variable, for example $Product["$dayIsPresent"] would not work, because there is not clear ending of the variable. For cases like these the variable must be enclosed in brackets to for it to be interpreted properly (e.g. $Product["{$day}IsPresent"]). For cases like yours where the variable is the last thing in the string, the brackets aren't necessary, but it doesn't hurt to add them if you prefer to.

If it's possible that in addition to having true or false values, $Product['hasMonday'] etc. may not actually be set, you can use !empty instead of simply evaluating that array key for truthiness.

if (!empty($Product["has{$day}"])) {