Fun With array_column()

Josh Pollock - April 29, 2015

  • array_column() is only available in PHP 5.5 or later. 😛
  • Figured this out for the example code demonstrating some cool new features in Caldera Forms 1.2
  • This is a little extra-complex due to my need to find the array key, as the function returns the (numeric) index.
  • I need a syntax highlighter, I know.
 
$a = array(
	'x' => array(
		'a' => 7,
		'b' => 8,
	),
	'y' => array(
		'a' => 2,
		'b' => 9,
	),
	'z' => array(
		'a' => 55,
		'b' => 'hats'
	)
);

//demonstrate how array_column works
var_dump( array_column( $a, 'b' ) ); //returns an array of all 'b' keys in array $a

//get the index (numeric) of array in $a with value of 1 for index 'b'
$index = array_search( 9, array_column( $a, 'b' ) ); // returns one, the (numeric) index of the array we want

//get numberic indexes of array
$indexes = array_keys( $a ); 

//get key for the index we want
$key = $indexes[ $index ]; //returns 'y'

var_dump( $key );