Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Renumbering Array Keys After Unsetting Value [duplicate]

Tags:

php

I use a PHP array to store data about all the people a user is following on a website. Here is an example of how I have it set up:

$data = array(
    ['user1'] => array(
        [0] => 'somedata',
        [1] => 'moredata',
        [2] => array(
            [0] => 'Jim',
            [1] => 'Bob',
            [2] => 'Nick',
            [3] => 'Susy',
        )
    ),
);

As you can see, it is $data[user][2] that lists all the friends. The array has this exact appearance with [0] and [1] for keys because that is how var_export() does it. Now my problem is this. When someone unfollows somebody, I use unset() to delete that friend from the array. So if I want to unfollow Bob in the example above, it would be left with Jim, Nick, and Susy.

The only issue now is that the array keys do not renumber properly when they rename. So once Bob is gone it goes from 0 to 2 rather than Nick taking on the array key of 1. Now I can think of ways to do this myself but I would highly prefer if there were some PHP function specifically for solving this issue, that is, renaming these array keys to the proper numerical order. I checked out the sort() function but that seems for alphabetizing array values not keys.

like image 659
Tai Kwangi Chicken Avatar asked Dec 04 '14 03:12

Tai Kwangi Chicken


People also ask

How to get duplicate value from array in PHP?

Definition and Usage. The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

How do I re index an array in PHP?

The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.

How to define an array key in PHP?

Syntax for indexed arrays: array(value1, value2, value3, etc.) Syntax for associative arrays: array(key=>value,key=>value,key=>value,etc.)

How to access PHP array elements?

Accessing Elements in a PHP Array The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]).


1 Answers

You can use array_values to re index the array numerically.

$newArray = array_values($array);
like image 117
Mohsin Rafi Avatar answered Oct 17 '22 20:10

Mohsin Rafi