views:

161

answers:

4

I have this piece of code I'm trying to get to display but no matter how I do it I just don't get any response or error whatsoever.

<?php
$day = array("Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo");
//$month[]= array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");

function today(){
    $d = date("N");
    switch ($d){
        case 1: 
            echo $day[1];
            break;
        case 2:
            echo $day[2];
            break;
        case 3:
            echo $day[3];
            break;
        case 4:
            echo $day[4];
            break;
        case 5:
            echo $day[5];
            break;
        case 6:
            echo $day[6];
            break;
        case 7:
            echo $day[7];
            break;
    }
} 
today();
?>

Can anyone see any obvious mistake I might be making and haven't noticed?

+2  A: 

Well i don't see a mistake, but you could just do

echo $day[date('N')-1];

you need to remember that array indexes start at 0 not 1. So $day[7] will give you index error because theres is no 7.

EDIT:

as paoloa bergantino pointed out. You need to make the $day variable global, or you could put it inside the scope of the function.

The.Anti.9
+4  A: 

You need to add

global $day;

At the top of your function.

Check out the PHP manual on variable scoping for more. In addition to that, as The.Anti.9 mentioned, you could just do:

$days = array("Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo");
function today() {
    global $days;
    echo $days[date("N")-1];
}
today();
Paolo Bergantino
Oh yes that is a good point, I didn't even notice it was out of scope.
The.Anti.9
+2  A: 

Since date('N') returns you the day of the week (1 - 7) you could create also an 1-based index array:

$day = array(1 => "Lunes","Martes","Miércoles","Jueves",
                  "Viernes","Sábado","Domingo");
echo $day[date('N')];
CMS
+2  A: 

To avoid using global variables (which is often-times a bad idea). You can just pass the variable in to the function.

Thus change the function declaration to

function today($day)

and the last function call to

today($day);

Note that the two $day's are not the same.

The function today($day) is simply saying that every $day variable within this function will contain the value that is passed in as this argument. It is not the array you declared. Therefore you can change this to whatever valid php variable name you want, along with all of the $days within the function scope and the result will remain the same.

The today($day) is saying pass in the Array $day that you declared before into the function today.

null