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].
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].
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 :
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 !
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.
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.
.
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;
++$index;
}
$return[$newKey] = is_array($value) ? reindex($value) : $value;
}
// Sort alphabetically, numeric first then alpha
ksort($return, SORT_NATURAL);
return $return;
}
Example here: http://ideone.com/969OGa
Use
array_values
.