same array_flatten function, compressed and preserving keys.
function array_flatten($a,$f=array()){
if(!$a||!is_array($a))return '';
foreach($a as $k=>$v){
if(is_array($v))$f=array_flatten($v,$f);
else $f[$k]=$v;
}
return $f;
}
array_values
(PHP 4, PHP 5)
array_values — Return all the values of an array
Description
array array_values
( array $input
)
array_values() returns all the values from the input array and indexes numerically the array.
Parameters
- input
-
The array.
Return Values
Returns an indexed array of values.
Examples
Example #1 array_values() example
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
The above example will output:
Array ( [0] => XL [1] => gold )

array_values
geo dot artemenko at gmail dot com
04-May-2010 07:37
04-May-2010 07:37
Carsten Milkau
01-Nov-2009 12:46
01-Nov-2009 12:46
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus "preserving keys" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.
<?php
/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/
function array_flatten_sep($sep, $array) {
$result = array();
$stack = array();
array_push($stack, array("", $array));
while (count($stack) > 0) {
list($prefix, $array) = array_pop($stack);
foreach ($array as $key => $value) {
$new_key = $prefix . strval($key);
if (is_array($value))
array_push($stack, array($new_key . $sep, $value));
else
$result[$new_key] = $value
}
}
return $result;
}
/*
* Flattening a multi-dimensional array into an
* n-dimensional one. The last n keys of each element are
* preserved. If this results in ambiguities, results are
* undefined.
*
* a[x_1][x_2]...[x_m] becomes a[x_{m-n+1}]...[x_m]
*/
function array_flatten_n($array, $n) {
$result = array();
$stack = array();
array_push($stack, array(array(), $array));
while (count($stack) > 0) {
list($prefix, $array) = array_pop($stack);
foreach ($array as $key => $value) {
if (is_array($value)) {
$new_prefix = array_values($prefix);
array_push($new_prefix, $key);
if (count($new_prefix) >= n)
array_shift($new_prefix);
array_push($stack, array($new_prefix, $value));
} else {
$array = $result;
foreach ($prefix as $pkey) {
if (!is_array($array[$pkey]))
$array[$pkey] = array();
$array = $array[$pkey];
}
$array[$key] = $value;
}
}
}
return $result;
}
?>
karl dot rixon at gmail dot com
18-Sep-2009 09:57
18-Sep-2009 09:57
A modification of wellandpower at hotmail.com's function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.
<?php
function array_values_recursive($array) {
$temp = array();
foreach ($array as $key => $value) {
if (is_numeric($key)) {
$temp[] = is_array($value) ? array_values_recursive($value) : $value;
} else {
$temp[$key] = is_array($value) ? array_values_recursive($value) : $value;
}
}
return $temp;
}
?>
id_ivan at yahoo dot com
08-Mar-2009 11:36
08-Mar-2009 11:36
i missed one array value for mistakenly putting the recursive function outside the loop. so here is the corrected function:
<?php
/* ---------------------
* @function array_flatten
* @param array
* @since 0.1
* @return array
* @notes flatten associative multi dimension array recursive
* @update 18:31 3/8/2009
* @author Rivanoor Bren <id_ivan(at)yahoo.com>
---------------------- */
function array_flatten($array, $preserve = FALSE, $r = array()){
foreach($array as $key => $value){
if (is_array($value)){
foreach($value as $k => $v){
if (is_array($v)) { $tmp = $v; unset($value[$k]); }
}
if ($preserve) $r[$key] = $value;
else $r[] = $value;
}
// this is correct
$r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
}
// wrong spot:
// $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
return $r;
}
?>
id_ivan at yahoo dot com
07-Mar-2009 03:29
07-Mar-2009 03:29
I finally found a way to solve my problem with multidimension array and though to share it here. This function flatten multi dimension (associative/index) array recursively while maintaining the key with its value. You can see the example for a better explanation.
<?php
/* ---------------------
* @function array_flatten
* @param array
* @since 0.1
* @return array
* @notes flatten associative multi dimension array recursive
* @update 22:02 3/7/2009
* @author Rivanoor Bren <id_ivan(at)yahoo.com>
---------------------- */
function array_flatten($array, $preserve = FALSE, $r = array()){
foreach($array as $key => $value){
if (is_array($value)){
foreach($value as $k => $v){
if (is_array($v)) { $tmp = $v; unset($value[$k]); }
}
if ($preserve) $r[$key] = $value;
else $r[] = $value;
}
}
$r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
return $r;
}
print_r($tmp);
/* ---
Array
(
[home] => Array
(
[id] => 1
[pid] => 0
[link] => home
[subcat] =>
)
[works] => Array
(
[id] => 2
[pid] => 0
[link] => works
[subcat] => Array
(
[viz] => Array
(
[id] => 4
[pid] => 2
[link] => viz
[subcat] =>
)
[script] => Array
(
[id] => 5
[pid] => 2
[link] => script
[subcat] => Array
(
[arch] => Array
(
[id] => 6
[pid] => 5
[link] => arch
[subcat] =>
)
)
)
)
)
[blog] => Array
(
[id] => 3
[pid] => 0
[link] => blog
[subcat] =>
)
)
--- */
print_r(array_flatten($tmp, 1));
/* ---
Array
(
[home] => Array
(
[id] => 1
[pid] => 0
[link] => home
[subcat] =>
)
[works] => Array
(
[id] => 2
[pid] => 0
[link] => works
)
[blog] => Array
(
[id] => 3
[pid] => 0
[link] => blog
[subcat] =>
)
[viz] => Array
(
[id] => 4
[pid] => 2
[link] => viz
[subcat] =>
)
[script] => Array
(
[id] => 5
[pid] => 2
[link] => script
)
[arch] => Array
(
[id] => 6
[pid] => 5
[link] => arch
[subcat] =>
)
)
--- */
?>
farum21 at hotmail dot com
03-Nov-2008 09:54
03-Nov-2008 09:54
Spent a few hours today figuring out a more elegant way to flatten an array:
<?php
$aNonFlat = array(
1,
2,
array(
3,
4,
5,
array(
6,
7
),
8,
9,
),
10,
11
);
$objTmp = (object) array('aFlat' => array());
array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
var_dump($objTmp->aFlat);
/*
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
[10]=>
int(11)
}
*/
?>
Anonymous
07-Oct-2008 01:44
07-Oct-2008 01:44
<?php
$array=array( 'value1'=>'value',
'array1'=> array( 'subItem1'=>'subItem1',
'subItem2'=>'subItem2' ),
'array2'=> array( 'subItem1'=>'subItem1' ));
$newArray=array();
array_flatten($array,$newArray);
print_r( $newArray );
//Output
//Array
//(
// [value1] => value
// [array1|subItem1] => subItem1
// [array1|subItem2] => subItem2
// [array2|subItem1] => subItem1
//)
// recursively reduces deep arrays to single-dimensional arrays
function array_flatten($array, &$newArray = Array() ,$prefix='',$delimiter='|') {
foreach ($array as $key => $child) {
if (is_array($child)) {
$newPrefix = $prefix.$key.$delimiter;
$newArray =& array_flatten($child, $newArray ,$newPrefix, $delimiter);
} else {
$newArray[$prefix.$key] = $child;
}
}
return $newArray;
}
?>
chrysb at gmail dot com
24-Sep-2008 07:34
24-Sep-2008 07:34
If you are looking for a way to count the total number of times a specific value appears in array, use this function:
<?php
function array_value_count ($match, $array)
{
$count = 0;
foreach ($array as $key => $value)
{
if ($value == $match)
{
$count++;
}
}
return $count;
}
?>
This should really be a native function of PHP.
madhamster
12-Jun-2008 11:18
12-Jun-2008 11:18
Good function, if you want to acces associative array element by position:
<?php
$array = array('fruit'=>'apple', 'juice'=>'orange', 'color'=>'lime');
$array = array_values($array);
echo $array[2];
?>
rene dot zak at post dot cz
24-Apr-2008 08:05
24-Apr-2008 08:05
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => ' ',
'fruit4' => ' ',
'fruit5' => 'apple');
for ($i = 0; $i < count($array); $i++) {
$key=key($array);
$val=$array[$key];
if ($val<> ' ') {
echo $key ." = ". $val ." <br> ";
}
next($array);
}
/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
EA
01-Feb-2008 11:36
01-Feb-2008 11:36
<?php
/*
array array_use_keys ( array $array_data , array $array_keys)
*/
function array_use_keys(&$array_data, &$array_keys)
// pre: $array_data != array(NULL)
// post: read only rows from $array_data having values from $array_keys for keys
// effective result: array{$array_data[$array_key[0]] .. $array_data[$array_key[n]]}
{
$resultarray = array();
foreach($array_keys as $key) // $key is the value of a element in $array_keys which is going to be used as a key
array_push($resultarray, $array_data[$key]); // note: array_push indexes with integers
return($resultarray);
}
?>
I only found the array_keys, yet it uses string, so I figured since I couldn't find a solution to make one of my own.
Hopefully this could make it into the next PHP in a improved array_keys;
PS
There are no sane errorchecks, so beware.
bluej100 at gmail dot com
07-Sep-2007 05:10
07-Sep-2007 05:10
Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).
<?
// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
foreach ($array as $key => $child) {
if (is_array($child)) {
$newArray =& array_flatten($child, $preserve_keys, $newArray);
} elseif ($preserve_keys + is_string($key) > 1) {
$newArray[$key] = $child;
} else {
$newArray[] = $child;
}
}
return $newArray;
}
// Tests
$array = Array(
'A' => Array(
1 => 'foo',
2 => Array(
'a' => 'bar'
)
),
'B' => 'baz'
);
echo 'var_dump($array);'."\n";
var_dump($array);
echo 'var_dump(array_flatten($array, 0));'."\n";
var_dump(array_flatten($array, 0));
echo 'var_dump(array_flatten($array, 1));'."\n";
var_dump(array_flatten($array, 1));
echo 'var_dump(array_flatten($array, 2));'."\n";
var_dump(array_flatten($array, 2));
?>
deceze at gmail dot YesThatsGoogleMail dot com
03-Sep-2007 07:31
03-Sep-2007 07:31
Please note that 'wellandpower at hotmail.com's recursive merge doesn't work. Here's the fixed version:
<?php
function array_values_recursive($array) {
$flat = array();
foreach ($array as $value) {
if (is_array($value)) $flat = array_merge($flat, array_values_recursive($value));
else $flat[] = $value;
}
return $flat;
}
?>
warmo_at_o2_dot_pl
22-Mar-2007 06:42
22-Mar-2007 06:42
@Yassin Ezbakhe <yassin88 at gmail dot com>
When we have to flatten multidimensional array of strings or numbers this method could be much faster.
Inconvenience of this method is, that its speed depends on size of strings/numbers, which array contains - bigger strings, lower efficiency.
Conclusion: Use this method for small amount of data in arrays (less than 500B per element in my case) which have many dimensions, in other case, use Yassin Ezbakhe method.
<?php
function md_implode($array, $glue = '')
{
if (is_array ($array))
{
$output = '';
foreach ($array as $v)
{
$output .= md_implode($v, $glue);
}
return $output;
}
else
{
return $array.$glue;
}
}
function md_array_flatten($md_array)
{
$flat_array = explode ('#|#',md_implode($md_array,'#|#')); // "#|#" is a sample delimiter
array_pop($flat_array); // to remove last empty element
return $flat_array;
}
//Usage:
$flat_array = md_array_flatten($some_md_array)
?>
ahigerd at stratitec dot com
24-Jan-2007 02:07
24-Jan-2007 02:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
wellandpower at hotmail.com
29-Aug-2006 12:56
29-Aug-2006 12:56
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.
I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.
In order to do this, you will want this function:
function array_values_recursive($array) {
$temp = array();
foreach ($array as $value) {
if(is_array($value)) { $temp[] = array_values_recursive($value); }
else { $temp[] = $value; }
}
return $temp;
}
Hopefully this will assist.
wizglins at gmx dot ch
13-Apr-2006 07:21
13-Apr-2006 07:21
In case you want to replace all keys in multiarrays by integers starting at 0, the following function might help.
<?php
function numerieren($array)
{
$array_v = array_values($array);
$count_v = count($array_v);
for ($i=0; $i<$count_v; $i++)
if (is_array($array_v[$i]))
$array_v[$i] = numerieren($array_v[$i]);
return $array_v;
}
?>
Yassin Ezbakhe <yassin88 at gmail dot com>
31-Aug-2005 11:28
31-Aug-2005 11:28
<?php
/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/
function array_values_recursive($array)
{
$arrayValues = array();
foreach ($array as $value)
{
if (is_scalar($value) OR is_resource($value))
{
$arrayValues[] = $value;
}
elseif (is_array($value))
{
$arrayValues = array_merge($arrayValues, array_values_recursive($value));
}
}
return $arrayValues;
}
?>
This function is an improved and faster version of the one posted by <27-Apr-2004 09:47>
kars at kde dot nl
24-May-2005 10:08
24-May-2005 10:08
Also, objects in the array that were added by reference are handled correctly as well:
class Foo {
var $n;
function Foo ($n) {
$this->n = $n;
}
}
$a = new Foo(1);
$b = new Foo(2);
$c = new Foo(3);
$l = array(&$a, &$b, &$c); // add by reference
$m = array_values($l);
$a->n = 5;
echo $m[0]->n;
This prints "5" as you would expect.
28-Apr-2004 01:47
<?php
/**
flatten an arbitrarily deep multidimensional array
into a list of its scalar values
(may be inefficient for large structures)
(will infinite recurse on self-referential structures)
(could be extended to handle objects)
*/
function array_values_recursive($ary)
{
$lst = array();
foreach( array_keys($ary) as $k ){
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge( $lst,
array_values_recursive($v)
);
}
}
return $lst;
}
?>
code till dawn! -mark meves!
cyberphant0m AT earthlink DOT net
28-Feb-2004 05:24
28-Feb-2004 05:24
That may be true, however I doubt that anyone should have that big of an array. If they do then they probably are doing some intense computing in which case, they may want to opt for the power of C++.
nopy at users dot sourceforge dot net
24-Oct-2003 10:36
24-Oct-2003 10:36
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.
For example, if your PHP momory_limits is 8MB,
and says there's a BIG array $bigArray which allocate 5MB of memory.
Doing this will cause PHP exceeds the momory limits:
<?php
$bigArray = array_values( $bigArray );
?>
It's because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.
04-Nov-2002 03:48
also useful to use for list(), if the array for input is the result of a function that only returns associative arrays:
list($var1, $var2, $var3) = array_values(myfunc("only returns assoc arrays"));
mailseppel at gmx dot de
04-Oct-2002 11:10
04-Oct-2002 11:10
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:
<?php
$row = mysql_fetch_array($db_result, $db_link);
?>
Hope I haven't misunderstood anything here.. :)
carl at thep.lu.se
29-Jan-2002 11:59
29-Jan-2002 11:59
Indeed you can, and that's what's so great about it. I have, for instance, a function that returns the results of a database query as an array. I want to keep the order that the entries were returned in, but at the same time I want to be able to access them _either_ by the position _or_ by some other index (such as some sort of ID in the database, gotten from elsewhere). In this case, I can make the function return an array from id to [array of values], and by a simple call to array_values() this is transformed into an array indexed from 0 to count()-1. Useful.
richard at phpguru dot org
19-Dec-2001 08:56
19-Dec-2001 08:56
If you have a numerically indexed array with some keys missing, ie 1, 2, 4, 5 and you want to reindex it so it's 1,2,3,4 *without changing the positions of the values* (ie sort()) then you can use this function to do it.