Returning Arrays in PHP, a simple example

Posted by on Aug 7, 2014 in Blog, PHP, Themes, Wordpress | No Comments

This one is just a little post for myself really. It may be handy for someone else. WordPress will often store data in Array in PHP. When you go to return something back by name you just get the result ‘Array’ Not very helpful.

First to create the array

<?php
$product_array = array("size" => "XL", "color" => "gold", "manufacturer" => "reebok", "price" => 37);
?>

To return all of the items in an Array and the keys

<?php
print_r($product_array);
?>

Will return
Array (
[size] => XL
[color] => gold
[manufacturer] => reebok
[price] => 37
)

To return just the items and their position in an Array

<?php
print_r(array_values($product_array));
?>

Will return
Array (
[0] => XL
[1] => gold
[2] => reebok
[3] => 37
)

To return just the keys

<?php
print_r(array_keys($product_array));
?>

Will return
Array (
[0] => size
[1] => color
[2] => manufacturer
[3] => price
)

Leave a Reply