Asked  7 Months ago    Answers:  5   Viewed   31 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].

 Answers

29

Use array_values.

$myarray = array_values($myarray);
Wednesday, March 31, 2021
 
Vlad
answered 7 Months ago
10

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 !

Wednesday, March 31, 2021
 
mertak
answered 7 Months ago
86

something like this perhaps:

function remove_adjacent_dups($arr) {
  $prev = null;
  $result = array();
  foreach( $arr as $val ) {
    if( $val !== $prev ) array_push($result, $val);
    $prev = $val;
  }
  return $result;
}
Wednesday, March 31, 2021
 
Sagar
answered 7 Months ago
33

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.

Friday, May 28, 2021
 
letrollpoilu
answered 5 Months ago
11

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.

.

Saturday, May 29, 2021
 
coolguy
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :