7

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.

4 Answers4

9

You can use array_values to re index the array numerically.

$newArray = array_values($array);
Mohsin Rafi
  • 539
  • 6
  • 14
1

If you just want to re-index the array at that level, you could simply use array_values();

For example, assuming you are removing the "bob" entry, just call array_values at the level directly above bob after removing it.

unset($data['user1'][2][1]);
$data['user1'][2] = array_values($data['user1'][2]);
ercmcd
  • 143
  • 1
  • 1
  • 9
1

I'd use array_values like this:

$data['user1'][2]=array_values($data['user1'][2]);

Here's the full code:

$data = array(
    'user1' => array(
        'somedata',
        'moredata',
        array(
            'Jim',
            'Bob',
            'Nick',
            'Susy',
        )
    ),
);

unset($data['user1'][2][1]);
var_export ($data['user1'][2]);

echo "\n\n";
$data['user1'][2]=array_values($data['user1'][2]);

var_export($data['user1'][2]);

Result

array (
  0 => 'Jim',
  2 => 'Nick',
  3 => 'Susy',
)

array (
  0 => 'Jim',
  1 => 'Nick',
  2 => 'Susy',
)

See it in action here: Sandbox

TecBrat
  • 3,643
  • 3
  • 28
  • 45
0

You could use array_splice

$removedElement = array_splice($data['user1'][2], $indexOfUserToRemove, 1);

This alters the original array reindexing it, but only if the keys of the array are numeric.

Juank
  • 6,096
  • 1
  • 28
  • 28