Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
Which is a better way to loop through an array in PHP?
foreach ( $arr as $a ){
   //some code
}

or

while ( $a = array_shift($arr) ){
   //some code
}

Which one should I use?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

According to php official website comments section,

Using array_shift over larger array was fairly slow. It sped up as the array shrank, most likely as it has to reindex a smaller data set.

array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.

If the array is too large, avoid using array_shift().

over 4 years ago · Santiago Trujillo Report

0

Using foreach is the preferred option. With it, you can bypass any structure that implements Traversable. If you have an indexed array, it is preferable to use for. The difference between ville and foreach shouldn't be too different. Preferred foreach. I also advise you to navigate your code, depending on the case.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!