Reputation: 65
I have an array like this
$array = array(
1 => 'one',
2 => 'two',
3 => 'three',
'row' => 'four',
'newRow' => 'five',
);
I need to re-index the numeric keys - 1, 2, 3.
Expected Output:
$array = array(
0 => 'one',
1 => 'two',
2 => 'three',
'row' => 'four',
'newRow' => 'five',
);
I've tried with array_values
, but the string keys also gets indexed.
What is the best way to do this?
Thanks.
Upvotes: 2
Views: 550
Reputation: 43594
Use array_merge
to reindex you array.
The code:
<?php
$array = array(
1 => 'one',
2 => 'two',
3 => 'three',
'row' => 'four',
'newRow' => 'five',
);
$reindexed_array = array_merge($array);
var_dump($reindexed_array);
The result:
array(5) {
[0]=> string(3) "one"
[1]=> string(3) "two"
[2]=> string(5) "three"
["row"]=> string(4) "four"
["newRow"]=> string(4) "five"
}
A working example you can find here: https://3v4l.org/Om72e. More information about array_merge
: http://php.net/manual/en/function.array-merge.php
Upvotes: 3
Reputation: 548
$array = array(
1 => 'one',
2 => 'two',
3 => 'three',
'row' => 'four',
'newRow' => 'five',
);
$newArray = [];
foreach ($array as $key => $value) {
if (!is_numeric($key)) {
$newArray[$key] = $value;
} else {
$newArray[] = $value;
}
}
var_dump($newArray);
die();
Upvotes: 1