Hi Guys,
Today, we will learn how to reindex the array key from 0 after the unset key. we can reassign the key using the array_values function of php. I will give you a simple example of reindexing an array from 0 after the unset key using the array_values function. we will reassign the keys from numeric like 0, 1, and 2, etc.
Sometimes you need to store JSON in the database column at that time it is better if you keep the array key as numeric with 0 1 2 etc. So we can do the JSON encode and JSON decode. So we can see in this example how you can make it done for reassigning array keys in PHP.
Example:
<?php
$myArray = ['0' => ['name' => 'Test 1', 'email' => 'test1@gmail.com', 'birthdate' => '01/01/1990', ], '1' => ['name' => 'Test 2', 'email' => 'test2@gmail.com', 'birthdate' => '01/01/1990', ], '2' => ['name' => 'Test 3', 'email' => 'test3@gmail.com', 'birthdate' => '01/01/1990', ], '3' => ['name' => 'Test 4', 'email' => 'test3@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...
0 Comments
Leave a Comment