Wednesday, 3 January 2018

Show All Array Keys and Values in PHP

Let's pretend you have a PHP array like the one below called "myArray", or any array for that matter that you wish to show both keys and values for in order to debug a scriipt or whatever purpose you have in mind.
First to be thorough, I'll show you quickly how to make a PHP array. The first code example below demonstrates an array's structure. The second is the actual "myArray" array we use in the rest of the code samples on this page.

Structure of a PHP Array

array_name = array(
'key_1' => 'value_1',
'key_2' => 'value_2',
'key_3' => 'value_3'
);

Example PHP Array:

myArray = array(
'firstname' => 'Ian',
'lastname' => 'Lin',
'password' => '1234'
);
Okay, good, now we have an array and if you didn't know how to make a PHP array, now you do! Let's say we want to show the contents of that array in our script so we can be sure it's working. Here are two methods that will show both keys and values stored in a PHP array. Each code example in green is followed by sample output in orange.
PHP Code to Show Keys and Values of an Array:
Example #1:
                foreach($myArray as $key=>$val){
                echo "<p style='color:orange'>$key) $val</p>";
                }//end foreach
Output:
firstname) Ian
lastname) Lin
password) 1234
Example #2:
echo "<hr /><pre>";
print_r($postarray);
echo "</pre>";
Output:
Array
(
[firstname] => Ian

[lastname] => Lin
[password] => 1234
)

Set Timezone for getDate PHP function

When I went to set the timezone for use with the getDate function in PHP today, I couldn't fine documentation for exactly that so I used what I did find to piece together the correct way to set a timezone within a PHP script for the getDate function. Here is how:
Example PHP Code:
<?php
//Set timezone:
date_default_timezone_set('America/New_York');
//format date:
$start = getdate();
$smon = $start['mon'];
$sday = $start['mday'];
$syear = $start['year'];
$shr = $start['hours'];
$smin = $start['minutes'];
$ssec = $start['seconds'];
$formatted_date =  "$smon-$sday-$syear"."_"."$shr-$smin-$ssec";
echo $formatted_date;
?>
The above PHP code will output:
 6-2-2014_11-24-23
For June, 2nd 2014 at 11:24:23am
By the way, the above format, 6-2-2014_11-24-23, I use for file names in applications that save data to a .txt file so I know when the file was saved by the PHP application and also so the file name will always be unique(as  long as it doesn't run faster than one per second in which case you will need to use milliseconds). Of course, you may change the format in the code above to format your date/time however you like.
List of U.S. Timezones to use with date_default_timezone_set function:

Eastern ........... America/New_York
Central ........... America/Chicago
Mountain .......... America/Denver
Mountain no DST ... America/Phoenix
Pacific ........... America/Los_Angeles
Alaska ............ America/Anchorage
Hawaii ............ America/Adak
Hawaii no DST ..... Pacific/Honolulu

How to Show Only Certain File Types:

In the next code snippet, I show you how to only show .html files from a specific directory. Here is that PHP code:
//path to directory to scan
$directory = "uploads/";
 
//get all files files with a .html extension.
$files = glob($directory . "*.html");
 
//print each file name
foreach($files as $filename)
{
echo $filename;
echo "<br>";
}

How to show Files and only Directories with Names and not dot or dotdot:


Notice the "." and the ".." those are directories in which you may not wish to show that represent the current directory and the parent directory respectively. To get redi of the dot and the dotdot, simply check for them like in the following code example:
<?php
//get the lastest file uploaded in uploads/
$path = "uploads";    
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
//Check whether the entry is a file etc.:
$latest_filename = $entry;
    if($latest_filename != "." && $latest_filename != "..") {
    $latest_filename = $entry;
    $file_type = filetype($filepath);//get file type.
    $file_size = filesize($filepath);//get file size.
    echo "$latest_filename<br />Type: $file_type<br />Size: $file_size<hr />";
    }//end if is file etc.
}//end while going over files in excel_uploads dir.
?>

How to Get Both Files and Directories:

To get both files and directories, the script is even simpler, simply take out the last if statement so your final code looks like:
//get ELEMENTS in uploads/
$path = "uploads";    
$d = dir($path);
    while (false !== ($entry = $d->read())) {
    $filepath = "{$path}/{$entry}";
    $latest_ctime = filectime($filepath);//like: 1402783996 that is timestamp so highest is latest.
    $latest_filename = $entry;
    $file_type = filetype($filepath);//get file type.
    $file_size = filesize($filepath);//get file size.
    echo "$latest_filename<br />Type: $file_type<br />Size: $file_size<hr />";
    }//end while going over files AND DIRECTORIES in uploads dir.

How to Get All File Names for a Directory with PHP

I fought with this for a while. I had to use PHP to return all file names in a directory with their respective size and types. I also had to return only files and not directories, but this guide will show you how to do both just in case you might need directories too.

Here is what the following code will return for a directory with three files in it:

Now here's the code that finally worked for me when I put the code in a file named get_file_names.php in the html directory which also held the "uploads" directory which it reads from :
//get the lastest file uploaded in uploads/
$path = "uploads";    
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
//Check whether the entry is a file etc.:
    if(is_file($filepath)) {
    $latest_filename = $entry;
    $file_type = filetype($filepath);//get file type.
    $file_size = filesize($filepath);//get file size.
    echo "$latest_filename<br />Type: $file_type<br />Size: $file_size<hr />";
    }//end if is file etc.
}//end while going over files in uploads dir.
Wrap that in PHP tags and you got your get_file_names.php script.


How to get Latest File Name from a Directory with PHP

Here is the code that will return the last file name uploaded to a directory using PHP:
<?php
//get the lastest file uploaded in excel_uploads/
$path = "uploads";
$latest_ctime = 0;
$latest_filename = '';    
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
//Check whether the entry is a file etc.:
    if(is_file($filepath) && filectime($filepath) > $latest_ctime) {
    $latest_ctime = filectime($filepath);
    $latest_filename = $entry;
    }//end if is file etc.
}//end while going over files in excel_uploads dir.
echo $latest_filename;
?>