1

I have a 0-based array

$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

I'd like to have it start at index one:

$days = [1 => 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

How could I do that, cleanest?

I have this but it's a bit ugly imo:

array_unshift($days, null);
unset($days[0]);
MightyPork
  • 18,270
  • 10
  • 79
  • 133

2 Answers2

2

The cleanest way to do this (with regards to dates) is to literally just use indexes directly.

Since you're refusing to use normal zero-based indexes, making a zero-based index and then incrementing all indexes would just be a bunch of magic that could very easily harm readability.

Literally, just do this:

$days = [
    1 => 'Mon',
    2 => 'Tue',
    3 => 'Wed',
    4 => 'Thu',
    5 => 'Fri',
    6 => 'Sat',
    7 => 'Sun',
];

Your intent is then crystal clear, and people wont be wondering what funky voodoo you did to a zero-indexed array.

Failing that, if you really have to, you can generate an array of values equal to the length of $days and use array_combine

$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$keys = range(1, count($days));
$new = array_combine($keys, $days);
Amelia
  • 2,967
  • 2
  • 24
  • 39
  • I don't think OP is necessarily 'refusing' to use zero-based indices. One major reason that comes to mind where they *must* use 1-based indices is if they are using PDO. – mcmurphy Dec 30 '19 at 19:02
1

Arrays are 0 based by default.

$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

Probably you need to change your array to an map key-value

// Original array
$days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

// Keys for the array
$keys = array(1,2,3,4,5,6,7);
$days = array_combine($keys, $days);

// Print the new array with keys
print_r($days);

// Access to array $days[1] ...

Result:

 Array ( [1] => Mon [2] => Tue [3] => Wed [4] => Thu [5] => Fri [6] => Sat [7] => Sun ) 

If the array is static in your code you could do this directly:

$days = array(1=>'Mon', 2=>'Tue', 3=>'Wed', 4=>'Thu', 5=>'Fri', 6=>'Sat', 7=>'Sun');

Also is possible to use the array with zero index based using the $index that is required minus 1

$value = $days[ ($index -1 )];
Dubas
  • 2,855
  • 1
  • 25
  • 37