Skip to main content

Quickly cast array elements in PHP

It's not immediately obvious, but there is a concise way to cast all elements of an array to a single type.  It's all possible with the array_walk() function.

array_walk($test, function(&$value, $key){$value = (integer) $value;});

Used in an example it would look like this.

$sampleArray = array("one"=>"1", "two"=>"2", "three"=>3, "four"=>"4d");

var_dump($sampleArray);

array_walk($sampleArray, function(&$value, $key){$value = (integer) $value;});
//--------------------------------^ Required!             ^
//--------------------------------------------------------+ Type to cast to.

var_dump($sampleArray);

NOTE:  It's important to note that the ampersand is necessary.  See the note about references on the second argument of the array_walk() function documentation.

Comments