Unsetting elements of array in a for loop in php

Posted May 27th, 2011 in Snippets by Metod

I did something like this today:

  1. <?php
  2. $arr = ["some", "elements", "in", "array"];
  3.  
  4. for ($i = 0; $i < sizeof($arr); $i++) {
  5.     if (true) { // for sake of clarity
  6.         unset($arr[$i]);
  7.     }
  8. }

The loop never came to the final element of the array, therefore not checking all of them. What was the problem?

Since sizeof($arr) is calculated every time the loop comes around, it was returning less and less with every unset instead of returning the same value.

Solution:

  1. <?php
  2. $arr = ["some", "elements", "in", "array"];
  3.  
  4. $size = sizeof($arr);
  5.  
  6. for ($i = 0; $i < $size; $i++) {
  7.     if (true) { // for sake of clarity
  8.         unset($arr[$i]);
  9.     }
  10. }

That way you ensure that size is always the correct integer. And it will run faster.

Code snippet 3

Posted January 15th, 2011 in Snippets by Metod

At the moment I am doing some java programming. And since being primarily a php guy, I was wondering how to easily return an array from a method like you can in php:

  1. public function returnArray() {
  2.     return array(1, 2, 3);
  3. }

And I found a way which is quite nice:

  1. public int[] returnArray() {
  2.     return new int[]{1, 2, 3};
  3. }