working with arrays
PHP arrays are versatile data structures used to store multiple values in a single
variable. They can hold various data types, including numbers, strings, booleans, objects, and
even other arrays.
PHP Array Types
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
Working With Arrays
In this tutorial you will learn how to work with arrays, including:
Create Arrays
Access Arrays
Update Arrays
Add Array Items
Remove Array Items
Sort Arrays
Array Items
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);
storing data in arrays
arrays are special variables capable of holding multiple values within a single variable. There
are two primary ways to create arrays
<?php
$indexedArray = array("Apple", "Banana", "Orange");
$associativeArray = array("fruit1" => "Apple", "fruit2" => "Banana", "fruit3" => "Orange");
?>
Indexed Arrays: These arrays use numerical indices (starting from 0 by default) to access
elements.
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Output: Red
$cars = [
"Volvo",
"BMW",
"Toyota"
];
Adding Data to Arrays:
<?php
$numbers = [1, 2, 3];
$numbers[] = 4; // Adds 4 to the end of the array
print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
processing arrays with loops and iterations
Processing arrays in PHP with loops and iterations is a fundamental task, primarily
accomplished using the foreach loop, but also possible with for and while loops.
The PHP foreach loop - Loops through a block of code for each element in an array or each
property in an object.
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
The array above is an indexed array, where the first item has the key 0, the second has the key
1, and so on.
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($members as $x => $y) {
echo "$x : $y <br>";
}
Using Arrays with Forms
Using arrays with forms in PHP allows for the efficient handling of multiple related input
values. This is particularly useful for elements like checkboxes, multiple-select dropdowns,
or when collecting structured data.
Creating Array Inputs in HTML:
To send form data as an array to PHP, you need to append square brackets [] to
the name attribute of your HTML input fields.
<input type="checkbox" name="colors[]" value="red"> Red
<input type="checkbox" name="colors[]" value="green"> Green
<input type="checkbox" name="colors[]" value="blue"> Blue
Accessing Array Data in PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Accessing a simple array
if (isset($_POST['colors'])) {
$selectedColors = $_POST['colors'];
echo "Selected Colors: ";
foreach ($selectedColors as $color) {
echo $color . " ";
}
echo "<br>";
}
// Accessing an associative array
if (isset($_POST['user'])) {
$userData = $_POST['user'];
echo "User Name: " . $userData['name'] . "<br>";
echo "User Email: " . $userData['email'] . "<br>";
}
// Accessing a nested array
if (isset($_POST['address'])) {
$addressData = $_POST['address'];
echo "Street: " . $addressData['street'] . "<br>";
echo "City: " . $addressData['city'] . "<br>";
}
}
?>
Working with Array Functions
Array Introduction
The array functions allow you to access and manipulate arrays.
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "value
array_count_values() Counts all the values of an array
<?php
// An array that represents a possible record set returned from a database
$a = array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
),
array(
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
)
);
$last_names = array_column($a, 'last_name');
print_r($last_names);
?>
Working with Dates and Time
PHP offers robust functionalities for handling dates and times, primarily through
the date() function, strtotime() function, and the DateTime class.
Getting and Formatting Current Date/Time:
<?php
// Get current date in YYYY-MM-DD format
$currentDate = date('Y-m-d');
echo "Current Date: " . $currentDate . "\n";
// Get current date and time in a more readable format
$currentDateTime = date('l, F j, Y H:i:s');
echo "Current Date and Time: " . $currentDateTime . "\n";
?>