How to start array index from 1 in PHP

Last updated 4 years, 4 months ago | 11882 views 75     5

Tags:- PHP

PHP | Start array index from 1

To change the array index start from 1 instead of 0 can be done using array_unshift() and unset() function.

array_unshift() Function
The array_unshift() function inserts new elements to an array. The new array values will be inserted at the beginning of the array.

unset() Function
The unset() function destroys a variable.

 


Consider the following array, which contains the values starting with index 0

<?php

$ex_array = array("PHP","JAVA","C#","Python", "Javascript", "C");
 
print_r($ex_array);

?>

The output of the above example is:

Array 
( 
	[0] => PHP 
	[1] => JAVA 
	[2] => C# 
	[3] => Python
	[4] => Javascript
	[5] => C
) 

 

So for start the index from "1", two functions are used array_unshift() and unset()

let's check with an example

<?php

$ex_array = array("PHP","JAVA","C#","Python", "Javascript", "C");

array_unshift($ex_array,"");

unset($ex_array[0]);

?>

 

The output of the above example is:

Array
(
    [1] => PHP
    [2] => JAVA
    [3] => C#
    [4] => Python
    [5] => Javascript
    [6] => C
) 

In the above example array_unshift() function is used to set a blank value at index "0". After that unset() function is used to delete the "0" index from the array