1

My code for reference:

$data1 = date('d-m-Y');
$array = array();
$i = 0;
while($i < 20){
    $datagenerica = substr($data1,stripos($data1,'-'));
    $datagenerica = $i.$datagenerica;
    $data = date('w',strtotime($datagenerica));
    $array[] = $data;
    $i++;
}
$array = array_unique($array);
sort($array);

I need the numbers stored within this array to be converted to weekday names, for example: 1 = Sunday. I would also like to know if this can be done natively in PHP, or will it be necessary to use a library?

Ghoti
  • 737
  • 4
  • 19
Emanoel José
  • 125
  • 1
  • 6
  • I know I can just make an array with the names of the days of the week, but I want to make a universal code that works with everyone's calendar. I also accept tips on how to do this in another way. – Emanoel José Jul 22 '21 at 03:59
  • What do you mean by "everyone's calendar?" Why not just make an array with days of the week and use the values of `$array` as indexes into that array of weekdays? – kmoser Jul 22 '21 at 04:06
  • could you give the actual result of the array? and put some details – Jerson Jul 22 '21 at 04:17
  • if you put the array of weekdays name and get the name according to indexes, it will also work with everyone's calendar as per the date as you wrote above. – PHP Geek Jul 22 '21 at 06:03

1 Answers1

1

I think with "with everyone's" you want to create the array with the names of the days of the week in a certain language. The IntlDateFormatter together with DateTime is the right class for this.

$lang = 'es';
$IntlDateFormatter = new IntlDateFormatter(NULL,NULL,NULL);
$weekdays = [];

//Here you can specify with which day of the week the array should begin.
$date = date_create("last Monday");

for($i=0; $i<7;$i++){
  $weekdays[] = $IntlDateFormatter->formatObject($date,"EEEE",$lang);
  $date->modify("+1 Day"); 
}

//test output
echo '<pre>';
var_export($weekdays);

Output:

array (
  0 => 'lunes',
  1 => 'martes',
  2 => 'miércoles',
  3 => 'jueves',
  4 => 'viernes',
  5 => 'sábado',
  6 => 'domingo',
) 
jspit
  • 7,276
  • 1
  • 9
  • 17