Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase by 1 all keys in an array?

Tags:

arrays

php

What is the simplest solution to increase by 1 all keys in an array?

BEFORE:

$arr[0] = 'a'; $arr[1] = 'b'; $arr[2] = 'c'; 

AFTER:

$arr[1] = 'a'; $arr[2] = 'b'; $arr[3] = 'c'; 
like image 379
Stanislav Avatar asked Oct 03 '12 19:10

Stanislav


People also ask

How do you increment values in an array?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

Can array have duplicate keys?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.

Can an array have keys?

No. Arrays can only have integers and strings as keys.


1 Answers

You can use

$start_zero = array_values($array); /* Re-Indexing Array To Start From Zero */ 

And if you want to start it from index 1 use

$start_one = array_combine(range(1, count($array)), array_values($array)); 
like image 106
Mr. Alien Avatar answered Sep 25 '22 18:09

Mr. Alien