Viewed   147 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

4

Use array_values.

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

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
 
mip
 
mip
1

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
 
drv
 
drv
5

You can simply use foreach instead like as

foreach($your_arr as &$v){
    $v = [$v["period"] => $v["way"]];
}
print_r($your_arr);

Or using array_map

$your_arr = array_map(function($v){ return [$v["period"] => $v["way"]]; },$your_arr);
print_r($your_arr);
Sunday, September 11, 2022
3

Just loop through and find unique values as you go:

$taken = array();

foreach($items as $key => $item) {
    if(!in_array($item['x'], $taken)) {
        $taken[] = $item['x'];
    } else {
        unset($items[$key]);
    }
}

Each the first time the x value is used, we save it - and subsequent usages are unset from the array.

Wednesday, September 21, 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 :