Asked  2 Years ago    Answers:  5   Viewed   140 times

I have array that i had to unset some indexes so now it looks like

$myarray [0] a->1
         [1] a-7 b->3
         [3] a-8 b->6
         [4] a-3 b->2

as you can see [2] is missing all i need to do is reset indexes so they show [0]-[3].



Use array_values.

$myarray = array_values($myarray);
Sunday, October 30, 2022

That is just not the way strings / array work, in PHP.

In PHP, "a" and "A" are two different strings.
Array keys are either integers or strings.

So, $a["a"] and $a["A"] point to two distinct entries in the array.

You have two possible solutions :

  • Either always using lower-case (or upper-case) keys -- which is probably the best solution.
  • Or search through all the array for a possible matching key, each time you want to access an entry -- which is a bad solution, as you'll have to loop over (in average) half the array, instead of doing a fast access by key.

In the first case, you'll have to use strtolower() each time you want to access an array-item :

$array[strtolower('KEY')] = 153;
echo $array[strtolower('KEY')];

In the second case, mabe something like this might work :
(Well, this is a not-tested idea ; but it might serve you as a basis)

if (isset($array['key'])) {
    // use the value -- found by key-access (fast)
else {
    // search for the key -- looping over the array (slow)
    foreach ($array as $upperKey => $value) {
        if (strtolower($upperKey) == 'key') {
            // You've found the correct key
            // => use the value

But, again it is a bad solution !

Sunday, November 6, 2022

The easiest way would probably to use foreach and make a new array... like this:

$new = array();
foreach($arr as $k=>$v) {
    $new[$k+1] = $v; // either increase
    $new[$k-1] = $v; // or decrease

You can also perform the operation by passing the original array by reference.

Thursday, November 3, 2022

An array is a collection of Elements.
Every element has key & value. Key can be a integer(index) or a string.
In you case

array($a, $b, $c, $d=>$e)

can be rewritten as

array(0 => $a, 1 => $b, 2 => $c, $d => $e);  

Where 0, 1, 2, $d are the keys of the array.
You can refer 0, 1, 2 as a index for value $a,$b,$c respectively and $d is a key for $e.


Tuesday, October 18, 2022

Here is a method that will only reindex numeric values:

function reindex($array)
    $index = 0;
    $return = [];

    foreach ($array as $key => $value) {
        if (is_string($key)) {
            $newKey = $key;
        } else {
            $newKey = $index;

        $return[$newKey] = is_array($value) ? reindex($value) : $value;

    // Sort alphabetically, numeric first then alpha
    ksort($return, SORT_NATURAL);

    return $return;

Example here:

Wednesday, October 19, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages