N in this question means any arbitrary number of any size and is not necessarily (but could be) the same. I have an array with N number of key => value pairs. These key => value pairs can also contain another array of size N with N number of key => value pairs. This array can be of N depth, meaning any key => value pair in the array could map to another array.How do I get all the values of this array (storing them in a new, 1 dimensional array), ignoring the keys in the key => value pairs?
Asked
Active
Viewed 159 times
3 Answers
2
rob at yurkowski dot net 26-Oct-2010 06:16
If you don't really particularly care about the keys of an array, you can capture all values quite simply:
$sample = array(
'dog' => 'woof',
'cat' => array(
'angry' => 'hiss',
'happy' => 'purr'
),
'aardvark' => 'kssksskss'
);
$output = array();
// Push all $val onto $output.
array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &$output);
// Printing echo nl2br(print_r($output, true));
/*
* Array
* (
* [0] => woof
* [1] => hiss
* [2] => purr
* [3] => kssksskss
* )
*/

Community
- 1
- 1

teemitzitrone
- 2,250
- 17
- 15
-
While this does seem to be the best answer, my only qualms are that this functionality is only supported by PHP >=5.3 . But still this would be the best way to do it. – bmarti44 Nov 05 '10 at 14:50
-
edit to my previous comment, inline PHP and functions are only supported by PHP >=5.3 . If this function used just a reference to a function, it would work in older versions of PHP. – bmarti44 Nov 05 '10 at 15:42
1
You could do smt like this:
$output = array();
function genArray( $arr ) {
global $output;
foreach( $arr as $key => $val ) {
if( is_array($val) )
genArray( $val );
else
output[$key] = $val;
}
}
genArray( $myArray );
Instead of recursion, using global variable and function, it could be done via loops, but this is just a general idea, and probably needs a little of your attention, anyway. That should be a good thing :)

hummingBird
- 2,495
- 3
- 23
- 43
-
1With an older version of PHP, this is the best solution. I would remove the global variable and just return it in the function though. – bmarti44 Nov 05 '10 at 14:52
-
-
Ah, I see you can't return it in this case. That would be returning an array element, you are correct. – bmarti44 Nov 05 '10 at 15:16
-
@bmarti44: i do think that there is a more elegant solution :). maybe using passing args by reference? – hummingBird Nov 05 '10 at 15:21
-
Yes, be specifying a second empty array and passing it by reference you would be able to remove the need of the global variable. That would most likely be the best answer. – bmarti44 Nov 05 '10 at 15:27
0
There are a ton of solutions in the comments of the array_values php doc.

Parris Varney
- 11,320
- 12
- 47
- 76