Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create array of a week days name in php

Tags:

php

I know this is stupid, but how would I do this? I would like to create an array of seven days through PHP What I mean is all the seven weekdays. I don't want to write them like his:

sunday monday tuesday ...etc

and days will be starting from sunday which means if today is the 29th of march (monday) then it automatically grabs the current date and create an array of weekdays starting from Sunday.

array always be in this way

 $weakarray=("sunday","monday",......,"saturday");
like image 857
diEcho Avatar asked Mar 29 '10 09:03

diEcho


3 Answers

This might work..

$timestamp = strtotime('next Sunday');
$days = array();
for ($i = 0; $i < 7; $i++) {
    $days[] = strftime('%A', $timestamp);
    $timestamp = strtotime('+1 day', $timestamp);
}
like image 100
Thiago Belem Avatar answered Oct 06 '22 00:10

Thiago Belem


If they always need to start with Sunday why do you want to create the array dynamically? What is wrong with doing this?

$days = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
];

Any other solution is going to make your code harder to understand and in this case doing it dynamically seems to be overkill.

like image 20
Yacoby Avatar answered Oct 06 '22 01:10

Yacoby


A little late answer, modification of the accepted as the best answer

<?php
    $days = array();
    for ($i = 0; $i < 7; $i++) {
        $days[$i] = jddayofweek($i,1);
    }
?>

Result:

array(7) { 
  [0]=> "Monday"
  [1]=> "Tuesday" 
  [2]=> "Wednesday" 
  [3]=> "Thursday" 
  [4]=> "Friday" 
  [5]=> "Saturday" 
  [6]=> "Sunday" 
}

See PHP's jddayofweek

like image 25
Rumen Tabakov Avatar answered Oct 05 '22 23:10

Rumen Tabakov