note 126953 modified in function.array-column by danbrown

From: Date: Sun, 03 Apr 2022 20:53:35 +0000
Subject: note 126953 modified in function.array-column by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218002@lists.php.net to get a copy of this message
The following function may be useful to create columns from all values of indexed arrays: <?php function array_column_all(array $arrays): array { $output = []; $columnCount = count($arrays[0]); for ($i = 0; $i < $columnCount; $i++) { $output [] = array_column($arrays, $i); } return $output; } ?> Use: ----- <?php array_column_all( [ ['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3'], ] ); ?> This will output: ------------------- Array ( [0] => Array ( [0] => A1 [1] => B1 [2] => C1 ) [1] => Array ( [0] => A2 [1] => B2 [2] => C2 ) [2] => Array ( [0] => A3 [1] => B3 [2] => C3 ) ) --was-- The following function may be useful to create columns from all values of indexed arrays: function array_column_all(array $arrays): array { $output = []; $columnCount = count($arrays[0]); for ($i = 0; $i < $columnCount; $i++) { $output [] = array_column($arrays, $i); } return $output; } Use: ----- array_column_all( [ ['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3'], ] ); This will output: ------------------- Array ( [0] => Array ( [0] => A1 [1] => B1 [2] => C1 ) [1] => Array ( [0] => A2 [1] => B2 [2] => C2 ) [2] => Array ( [0] => A3 [1] => B3 [2] => C3 ) ) https://php.net/manual/en/function.array-column.php

« previous php.notes (#218002) next »