- PHP Basics
- Learn PHP
- PHP Comments
- PHP Data Types
- PHP Variables
- PHP Operators
- PHP echo
- PHP print
- PHP echo vs. print
- PHP if else
- PHP switch
- PHP for Loop
- PHP while Loop
- PHP do...while Loop
- PHP foreach Loop
- PHP break and continue
- PHP exit()
- PHP exit() vs. break
- PHP isset()
- PHP Arrays
- PHP print_r()
- PHP unset()
- PHP Strings
- PHP Functions
- PHP File Handling
- PHP File Handling
- PHP Open File
- PHP Create a File
- PHP Write to File
- PHP Read File
- PHP feof()
- PHP fgetc()
- PHP fgets()
- PHP Close File
- PHP Delete File
- PHP Append to File
- PHP Copy File
- PHP file_get_contents()
- PHP file_put_contents()
- PHP file_exists()
- PHP filesize()
- PHP Rename File
- PHP fseek()
- PHP ftell()
- PHP rewind()
- PHP disk_free_space()
- PHP disk_total_space()
- PHP Create Directory
- PHP Remove Directory
- PHP Get Files/Directories
- PHP Get filename
- PHP Get Path
- PHP filemtime()
- PHP file()
- PHP include()
- PHP require()
- PHP include() vs. require()
- PHP mysqli Tutorial
- PHP mysqli Tutorial
- PHP and MySQL Setup
- PHP mysqli: Create Database
- PHP mysqli: Create Table
- PHP mysqli: Insert Record
- PHP mysqli: Update Record
- PHP mysqli: Fetch Record
- PHP mysqli: Delete Record
- PHP mysqli: SignUp Page
- PHP mysqli: LogIn Page
- PHP mysqli: Store User Data
- PHP mysqli Functions
- PHP mysqli_connect()
- PHP mysqli_close()
- PHP mysqli_connect_errno()
- PHP mysqli_connect_error()
- PHP mysqli_query()
- PHP mysqli_fetch_row()
- PHP mysqli_fetch_assoc()
- PHP mysqli_fetch_array()
- PHP mysqli_free_result()
- PHP mysqli_error()
- PHP mysqli_prepare()
- PHP mysqli_stmt_bind_param()
- PHP mysqli_stmt_execute()
- PHP mysqli_stmt_fetch()
- PHP mysqli_stmt_store_result()
- PHP mysqli_stmt_num_rows()
- PHP mysqli_stmt_bind_result()
- PHP mysqli_stmt_get_result()
- PHP mysqli_result class
- PHP mysqli_report()
- PHP error_reporting()
- PHP mysqli_real_escape_string()
- PHP htmlspecialchars()
- PHP Misc Topics
- PHP Object Oriented
- PHP new Keyword
- PHP header()
- PHP getallheaders()
- PHP Cookies
- PHP Sessions
- PHP Date and Time
- PHP GET vs. POST
- PHP File Upload
- PHP Image Processing
Arrays in PHP with examples
In PHP, we use an array when we need to store multiple values in a single variable.
How do we create an array in PHP?
We use the "array()" function when we need to create an array in PHP. The syntax of the "array()" function to create an array is as follows:
arrayVariableName = array(item1, item2, item3,..., itemN);
The "array()" can be considered a constructor. "item1", "item2", "item3", and so on. are the items of the array named "arrayVariableName". For example:
$students = array("William", "Edwin", "Lucas", "Julia");
PHP array example
Consider the following PHP code as an example of an array in PHP:
<?php $students = array("William", "Edwin", "Lucas", "Julia"); print_r($students); ?>
Array ( [0] => William [1] => Edwin [2] => Lucas [3] => Julia )
The "print_r()" function is used to print an array, object, or variable's contents in a human-readable format. It is defined in the next post.
Find the length of an array in PHP
To find the length of an array in PHP, use the "count()" function. For example:
<?php $students = array("William", "Edwin", "Lucas", "Julia"); $studentsLength = count($students); echo $studentsLength; ?>
4
Access array items using the index value in PHP
Because indexing in an array starts with 0, "students[0]" refers to the very first item of the array, which is "William" based on the previously defined array. For example:
<?php $students = array("William", "Edwin", "Lucas", "Julia"); echo "First item: ", $students[0]; echo "<BR>"; echo "Second item: ", $students[1]; echo "<BR>"; echo "Third item: ", $students[2]; echo "<BR>"; echo "Fourth item: ", $students[3]; ?>
First item: William Second item: Edwin Third item: Lucas Fourth item: Julia
Another way that we can approach printing the array items is as follows:
<?php $students = array("William", "Edwin", "Lucas", "Julia"); echo "Items = ". $students[0].", ". $students[1].", ". $students[2].", and ". $students[3]; ?>
Items = William, Edwin, Lucas, and Julia
Print all items of an array using a loop in PHP
The previous method, on the other hand, is not recommended because it is not possible to write the array items manually if the items of the array are unknown. Therefore, we need to loop through the array. For example:
<?php $stds = array("William", "Edwin", "Lucas", "Julia"); $sLen = count($stds); for($i = 0; $i < $sLen; $i++) { echo $stds[$i]; echo "<BR>"; } ?>
William Edwin Lucas Julia
All the arrays that are discussed above come under the type "indexed array in PHP". However, there are other two types of arrays available in PHP, which are "associative array" and "multi-dimensional array". So let's discuss these two other types of arrays one by one, starting with the "associative array".
PHP associative array
An associative array in PHP is a type of array where accessing its elements is done through string keys rather than numerical indices. The values, which can be of any data type, including other arrays, are linked to the corresponding keys.
The general form to create an associative array in PHP is as follows:
$myarray array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ... );
PHP associative array example
<?php $stds = array( 'name' => 'Edwin', 'age' => 26, 'city' => 'Houston' ); echo $stds['name']; echo "<BR>"; echo $stds['age']; echo "<BR>"; echo $stds['city']; ?>
Edwin 26 Houston
However, we can also use loop to print the items of an associative array. Consider the following PHP code as an example demonstrating the printing of an associative array through a loop.
<?php $stds = array( 'name' => 'Edwin', 'age' => 26, 'city' => 'Houston' ); foreach($stds as $k => $v) { echo $k . " = " . $v; echo "<BR>"; } ?>
name = Edwin age = 26 city = Houston
Modify an existing element and add a new key-value pair
We can also update the value of any key that is already available in the PHP associative array. In addition, we can also add new items. Consider the following PHP code as an example demonstrating this concept:
<?php $stds = array( 'name' => 'Edwin', 'age' => 26, 'city' => 'Houston' ); echo "<p>Before modification</p>"; foreach($stds as $k => $v) { echo $k . " = " . $v; echo "<BR>"; } $stds['name'] = 'William'; $stds['gender'] = 'male'; echo "<hr><p>After modification</p>"; foreach($stds as $k => $v) { echo $k . " = " . $v; echo "<BR>"; } ?>
Before modification name = Edwin age = 26 city = Houston
After modification name = William age = 26 city = Houston gender = male
PHP multidimensional array
In PHP, a multi-dimensional array is an array that itself contains another array (or more than one). Multidimensional arrays allow each element to be another array, effectively creating a hierarchy of arrays. For example:
$myarray = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) );
In this example, $myarray is a two-dimensional array with three sub-arrays, each of which has three integer values.
PHP multidimensional array example
<?php $myarray = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9), array(10, 11, 12) ); for($i=0; $i<4; $i++) { for($j=0; $j<3; $j++) { echo $myarray[$i][$j]; echo " "; } echo "<BR>"; } ?>
1 2 3 4 5 6 7 8 9 10 11 12
This PHP code creates a 2-dimensional array called $myarray, iterates through its elements, and prints them to the output using two nested for loops.
To represent a 4x3 matrix, the array is initially initialized with four sub-arrays, each containing three integer values.
Starting with the first sub-array and moving row by row, the two for loops are used to iterate over each element of the array. The inner loop iterates over the matrix's columns while the outer loop iterates over the matrix's rows.
The echo statement is used by the code to print each element of the array to the output within the inner loop, followed by a space character. This actually prints the matrix's elements one after the other, separated by spaces.
The code uses the echo statement to print a line break (<BR>) to advance to the next line in the output after the inner loop has finished for each row. This results in a formatted output that presents the matrix's components as a grid with each row on its own line.
« Previous Tutorial Next Tutorial »