Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_values

array_values

Return all the values of an array (PHP 4, PHP 5)
array array_values ( array input )

Example 289. 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
) ?>

Related Examples ( Source code ) » array_values



Code Examples / Notes » array_values

wellandpower

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.


cyberphant0m

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++.

mailseppel

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.. :)


deceze

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;
}
?>


bluej100

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));
?>


nopy

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.


carl

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.

wizglins

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;
}
?>


richard

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.

kars

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.


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"));


ahigerd

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


warmo_at_o2_dot_pl

@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)
?>


yassin ezbakhe
<?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>


28-apr-2004 02: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!


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker