PHP – Foreach By Reference

Today I was writing some code in which I wanted to modify the values of an array within a for-loop. The obvious solution would be to use the key to modify the value but there is actually another way of doing it:

$arr = array(1,2,3,4,5);
foreach ($arr as &$value) {
  $value = $value * $value;
}
print_r($arr);

The above code will actually go through the array of integers 1 to 5 and change the array to be the squares of those values. The output is as follows:

Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

This works because placing the ampersand in front of the $value makes the variable refer to the actual value within the array and updating it will update the value within the array.

JavaScript – Parsing A Number

If you should ever need to parse a number into an array of bits or a different base you can use the following function:

var splitNumber = (function(MAX) {
  for (; MAX + 1 - MAX == 1; MAX *= 2){}
  return function (num, radix) {
    // Validate num
    num = parseInt(num, 10);
    if (!isFinite(num) || 0 > num || num > MAX) {
      throw new Error('splitNumber() num argument must be a non-negative finite number less than ' + MAX);
    }
 
    // Validate radix
    radix = parseInt(radix || 10, 10);
    if (!(1 < radix && radix <= MAX)) {  // Also prevents NaN
      throw new Error('splitNumber() radix argument must be greater than 2 and less than ' + MAX);
    }
 
    return num.toString(radix).split('');
  };
})(1 << 30);

Here is an example of the tests and outputs:

I want to thank ildar for contributing the refinement of this function. 😎

EcmaScript 6 – Array.of()

A function that is proposed to be added to EcmaScript 6 is Array.of(). This function will be used to create an array of the passed parameters. Since this function is available in some browsers but not in all, here is a block of code which when executed will define it if not already defined:

Array.of = Array.of || function() {
  return Array.prototype.slice.call(arguments);
};

Here are some examples of using the function:

var a = Array.of(1,2,3);     // [1,2,3]
var b = Array.of();          // []
var c = Array.of(undefined); // [undefined]
var d = Array.of(null);      // [null]
var e = Array.of(4);         // [4]

Not the most amusing function, but it is still a step towards EcmaScript 6. 😎