Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why array_values is better than a foreach?

Tags:

arrays

php

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?

like image 961
Romain Sickenberg Avatar asked Dec 18 '22 04:12

Romain Sickenberg


1 Answers

  1. Less code.
  2. Easier to understand code, because that's exactly what array_values is for, yet your foreach could do anything unless you read and understand it.
  3. array_values is a native PHP function implemented in C behind the scenes, and likely much more performant than custom PHP code.
like image 140
deceze Avatar answered Jan 04 '23 08:01

deceze