Why array_values()
is better than a foreach loop to re-index an array?
Example 1:
$arrays = [
1 => '0',
2 => '1',
3 => '2',
4 => '3',
5 => '',
6 => '',
7 => '7',
8 => [
0 => 'toto',
1 => 'manu',
2 => 'noé',
3 => 'david'
]
];
$arrayNonAssoc = [];
foreach ($arrays as $array) {
$arrayNonAssoc[] = $array;
}
So the Example 1 is the error to not do and...
Example 2:
$arrays = [
1 => '0',
2 => '1',
3 => '2',
4 => '3',
5 => '',
6 => '',
7 => '7',
8 => [
0 => 'toto',
1 => 'manu',
2 => 'noé',
3 => 'david'
]
];
var_dump(array_values($arrays));
I have read about it, but I didn't found any explications to this. Both Example 1 and Example 2 return the same result...
Is it about performance?
array_values
is for, yet your foreach
could do anything unless you read and understand it.array_values
is a native PHP function implemented in C behind the scenes, and likely much more performant than custom PHP code.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With