Categories: Development

Printing array keys and values with PHP

Being able to quickly or efficiently get the keys from an array which is most likely an API call is great. You can see what data exists which may not be clear in the docs (if they exist).

Here is a method with PHP to print out an array keys and values, you can even shape the loop to create a CREATE TABLE query using the keys for column names or even creating an INSERT query.

This example i am using the Reddit API, this is a multi dimensional array and you can see for the foreach i further define the row for which i want to get the keys and values for.

Printing array keys & values

The basic code with no formatting or style is:

 $value) {
    echo "$key : $value
"; }

[0]['data']['children'][0]['data'] points to the part with the keys i am after. Load up the http://www.reddit.com/r/pics/c1wqkk.json call in a json formatter to see multi dimensions to this call.

If you run the code above you will notice a few errors for trying to parse arrays, that is because there is still another layer (dimension) you can go into. However these are mostly always empty for this call.

The booleans also do not get displayed (true and false), nor empty strings (“”).

Formatting and adding style

To add some formatting to display the values accurately for their type here is an added function plus a little bit of CSS to make readability better:

 $value) {
    echo "

$key

:

" . format_value_type($value) . "


"; }

This looks like

Some of the output

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago