Jordan Newton
Jordan Newton

Reputation: 119

use array in foreach statement based on if condition

Is it possible to select an array to use in a foreach statement can't figure it out :/

My Code:

<?php
$selmon = $_GET['m'];
$selectmon = ('$' . $months[$selmon-1]);
foreach ($selectmon as $day){
if ($day % 7 == 0){
echo ("<td>" . $day . "</td>");
echo ("</tr>");
echo ("<tr>");
}else{
echo ("<td>" . $day . "</td>"); 
}}
?>

My arrays basically contain a list of all the days in the month e.g.?

$september = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30);

Am I going about this the wrong way or is it even possible?

Also I have an array of the month names:

$months = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");

and if i use

echo $selectmon;

If i use localhost/index.php?m=1 it returns

$january 

Upvotes: 0

Views: 1489

Answers (2)

Leah Zorychta
Leah Zorychta

Reputation: 13449

You were close. You need to do ${$months[$selmon-1]} and this is called accessing a variable dynamically:

<?php
$selmon = $_GET['m'];
$selectmon = ${$months[$selmon-1]};
foreach ($selectmon as $day){
  if ($day % 7 == 0){
    echo ("<td>" . $day . "</td>");
    echo ("</tr>");
    echo ("<tr>");
  }else{
    echo ("<td>" . $day . "</td>"); 
  }
}
?>

also, it's considered not the best practice to access variables in this way. Consider what would happen if you had a different scenario: echo ${$_GET['v']}. Now, if a user went to webpage.php?v=MYSQL_PASSWORD the code would read echo $MYSQL_PASSWORD. I'm sure you can imagine how this technique may reveal a security risk given certain circumstances. The way you're using dynamic variables wont run into this problem because in the worst case (where $months[#] is null) you are only exposing $null which does not matter so much.

Upvotes: 4

A. Sim
A. Sim

Reputation: 166

I'd recommend looking into the date() function instead. It's a lot easier to do rather than hardcoding your month lists, and your code will be a lot cleaner as well. Something like this:

$month = $_GET['m']-1;
$numDays = date("t", strtotime("2015-$month-01"));

will always display the number of days in the selected month. You can then write something like

for($day = 1; $day < $numDays + 1; $day++)
{
  echo "<td>$day</td>";
  if ($day % 7 == 0)
  {
    echo "</tr><tr>";
  }
}

You can also display month names, days of the week, or handle leap years, all with no arrays needed!

Upvotes: 2

Related Questions