ItSolutionStuff.com

PHP - How to Reindex Array Key After Unset Key?

By Hardik Savani • May 14, 2024
PHP

Today, we will learn how to reindex array key from 0 after unset key. we can reassign key using array_values function of php. i will give you simple example for reindex array from 0 after unset key using array_values function. we will reassign keys from numeric like 0 1 2 etc.

Sometime you need to store json to database column at that time it is better if you keep array key as numeric with 0 1 2 etc. so you can easily do json encode and json decode. so you can see in this example how you can make it done for reassign array keys in php.

Example:

<?php

$myArray = [

'0' => [

'name' => 'Paresh',

'email' => 'paresh@gmail.com',

'birthdate' => '01/01/1990',

],

'1' => [

'name' => 'Rakesh',

'email' => 'rakesh@gmail.com',

'birthdate' => '01/01/1990',

],

'2' => [

'name' => 'Mahesh',

'email' => 'mahesh@gmail.com',

'birthdate' => '01/01/1990',

],

'3' => [

'name' => 'Mahesh 2',

'email' => 'mahesh@gmail.com',

'birthdate' => '01/01/1990',

]

];

unset($myArray[2]);

$myArray = array_values($myArray);

print_r($myArray);

?>

Output:

Array

(

[0] => Array

(

[name] => Paresh

[email] => paresh@gmail.com

[birthdate] => 01/01/1990

)

[1] => Array

(

[name] => Rakesh

[email] => rakesh@gmail.com

[birthdate] => 01/01/1990

)

[2] => Array

(

[name] => Mahesh 2

[email] => mahesh@gmail.com

[birthdate] => 01/01/1990

)

)

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

PHP JQuery Chosen Ajax Autocomplete Example

Read Now →

PHP MySQL Login with Google Account Example

Read Now →

PHP Ajax Multiple Image Upload with Preview Example

Read Now →

How to Upload and Resize Image in PHP?

Read Now →

PHP Crop Image Before Upload using Croppie JS Example

Read Now →

How to Convert Object into Array in PHP?

Read Now →

How to Remove Specific Element by Value from Array in PHP?

Read Now →

How to Remove undefined Value from Array in JQuery?

Read Now →

How to Get Maximum Key Value of Array in PHP?

Read Now →

How to Remove Empty Values from Array in PHP?

Read Now →

How to Add Prefix in Each Key of PHP Array?

Read Now →

How to Get Minimum Key Value of Array in PHP?

Read Now →

How to Remove Null Values from Array in PHP?

Read Now →

How can Make an Array from the Values of Another Array's Key Value?

Read Now →