Setting up a page which wants to greet the user with the phrase “Good morning, today is Saturday” is a good example to show how to obtain the day of the week in PHP. And above all how to get the day of the week at PHP and show us the text in Spanish.
Using PHP date function
The first thing that comes to mind is to pull the PHP date. After all, it brings multiple ways to obtain date information.
In addition we have a modifier, which is «l», which returns the day of the week in PHP. So we get to work and write the following:
echo "Good morning, today is "date("l");
Up to this point it seems that it is very easy to obtain the day of the week at PHP (in the end it will be too). The problem is that we see that the program will tell us…
Good morning, today is Saturday
Wow, it appears in “Spanglish.” But let’s not despair, can we localize the date function by playing with the setlocale? Something like:
setlocale(LC_ALL,"es_ES");
But neither… and the function PHP date is not a function that works with localizations and therefore always returns the content in English.
Using PHP date function and an array
If we want to continue working with the function PHP date we should not despair since we can implement an alternative solution by defining an array with the values of the week.
$days = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
And now play with the «w» modifier of the function PHP date. And this modifier makes the function PHP date returns the day of the week in a number. We have already managed to make this number coincide with the position of the array, since 0 is Sunday and 6 is Saturday.
The code to use will be:
echo "Good morning, today is ".$days[date("w")];
Using the PHP strftime function
Like the function PHP date does not allow us to locate the text, we can use the function PHP strftime, which does work with the locale.
So the first thing is to use the setlocale for all «LC_ALL» functions.
setlocale(LC_ALL,"es_ES");
And now we will use strftime using the %A modifier, which indicates the day of the week. This is how we will put the following code:
echo strftime("Good morning, today is %A
");
Surely one of these two options will work for us to be able to put the day of the week in PHP.