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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago