How to get array data in php

❮ PHP Array Reference

Example

Return all the values of an array (not the keys):

<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>

Try it Yourself »


Definition and Usage

The array_values() function returns an array containing all the values of an array.

Tip: The returned array will have numeric keys, starting at 0 and increase by 1.


Syntax

Parameter Values

ParameterDescription
array Required. Specifying an array

Technical Details

Return Value:Returns an array containing all the values of an array
PHP Version:4+

❮ PHP Array Reference



An array stores multiple values in one single variable:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Try it Yourself »


What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.


Create an Array in PHP

In PHP, the array() function is used to create an array:

In PHP, there are three types of arrays:

  • Indexed arrays - Arrays with a numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays


Get The Length of an Array - The count() Function

The count() function is used to return the length (the number of elements) of an array:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

Try it Yourself »


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!


PHP Exercises



(PHP 4, PHP 5, PHP 7, PHP 8)

array_valuesReturn all the values of an array

Description

array_values(array $array): array

Parameters

array

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
)

See Also

  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_combine() - Creates an array by using one array for keys and another for its values

biziclop at vipmail dot hu

8 years ago

Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the 'foreach' ordering:

<?php
$a
= array(
3 => 11,
1 => 22,
2 => 33,
);
$a[0] = 44;print_r( array_values( $a ));
==>
Array(
  [
0] => 11
 
[1] => 22
 
[2] => 33
 
[3] => 44
)
?>

nopy at users dot sourceforge dot net

18 years ago

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.

abimaelrc

11 years ago

This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
* Get all values from specific key in a multidimensional array
*
* @param $key string
* @param $arr array
* @return null|string|array
*/
function array_value_recursive($key, array $arr){
   
$val = array();
   
array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if(
$k == $key) array_push($val, $v);
    });
    return
count($val) > 1 ? $val : array_pop($val);
}
$arr = array(
   
'foo' => 'foo',
   
'bar' => array(
       
'baz' => 'baz',
       
'candy' => 'candy',
       
'vegetable' => array(
           
'carrot' => 'carrot',
        )
    ),
   
'vegetable' => array(
       
'carrot' => 'carrot2',
    ),
   
'fruits' => 'fruits',
);
var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>

bluej100 at gmail dot com

15 years ago

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

Anonymous

18 years ago

<?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!

chrysb at gmail dot com

13 years ago

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.

How can we get particular data from array in PHP?

Answer: Use the Array Key or Index If you want to access an individual value form an indexed, associative or multidimensional array you can either do it through using the array index or key.

How do I get all the values of an array?

The array_values() function returns an array containing all the values of an array. Tip: The returned array will have numeric keys, starting at 0 and increase by 1.

How extract data from array explain with example in PHP?

The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

How can I print just the value of an array in PHP?

Answer: Use the PHP foreach loop php $colors = array("Red", "Green", "Blue", "Yellow", "Orange"); // Loop through colors array foreach($colors as $value){ echo $value . "<br>"; } ?>