Learn the fundamentals of PHP arrays with this comprehensive lesson. Explore the versatility of indexed arrays, discover the power of associative arrays, and delve into the complexity of multidimensional arrays. Gain practical insights through examples and understand how to use these array types in real-world applications.
In PHP, arrays are versatile data structures that can be used to store and manipulate collections of data. PHP supports several types of arrays, and they can be categorized into two main types: indexed arrays and associative arrays. Additionally, there is a special type called a multidimensional array that allows you to create arrays of arrays. Here’s an overview of these array types in PHP:
Indexed arrays are the most basic type of arrays in PHP.
Elements are assigned a numeric index starting from 0.
You can use the array() function or the shorthand [] syntax to create indexed arrays.
Example:
$colors = array("red", "green", "blue"); // or $colors = ["red", "green", "blue"];
Example:
$person = array(“name” => “Gogo”, “age” => 17, “city” => “Cairo”);
// or
$person = [“name” => “Omar”, “age” => 20, “city” => “Cairo”];
Example:
$matrix = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) );
PHP also has specialized array types like SplFixedArray, which is a fixed-size array, and SplDoublyLinkedList, which is a doubly linked list.
Example (SplFixedArray):
$fixedArray = new SplFixedArray(3); $fixedArray[0] = "apple"; $fixedArray[1] = "banana"; $fixedArray[2] = "orange";
These are the main types of arrays in PHP. Depending on your specific use case, you can choose the array type that best fits your requirements.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Indexed Array Example</title> </head> <body> <?php // Define an indexed array of colors $colors = ["red", "green", "blue"]; // Accessing and displaying elements of the array echo "<h2>Colors:</h2>"; echo "<ul>"; for ($i = 0; $i < count($colors); $i++) { echo "<li>$colors[$i]</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
The resulting HTML page will show a list of colors:
Colors:
– red
– green
– blue
You can save this code in a file with a .php extension and run it on a server with PHP support to see the output. This example is a basic illustration of using indexed arrays in PHP within an HTML context.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Associative Array Example</title> </head> <body> <?php // Define an associative array representing information about a person $person = [ "name" => "John Doe", "age" => 30, "city" => "New York" ]; // Accessing and displaying elements of the associative array echo "<h2>Person Information:</h2>"; echo "<ul>"; foreach ($person as $key => $value) { echo "<li><strong>$key:</strong> $value</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
The resulting HTML page will show information about the person:
Person Information:
– Name: John Doe
– Age: 30
– City: New York
You can save this code in a file with a .php extension and run it on a server with PHP support to see the output. This example is a basic illustration of using associative arrays in PHP within an HTML context.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multidimensional Array Example</title> </head> <body> <?php // Define a 2D array representing a matrix $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // Accessing and displaying elements of the 2D array echo "<h2>Matrix:</h2>"; echo "<table border='1'>"; foreach ($matrix as $row) { echo "<tr>"; foreach ($row as $value) { echo "<td>$value</td>"; } echo "</tr>"; } echo "</table>"; ?> </body> </html>
Explanation:
Matrix:
+—+—+—+
| 1 | 2 | 3 |
+—+—+—+
| 4 | 5 | 6 |
+—+—+—+
| 7 | 8 | 9 |
+—+—+—+
You can save this code in a file with a .php extension and run it on a server with PHP support to see the output. This example is a basic illustration of using multidimensional arrays in PHP within an HTML context.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SplFixedArray Example</title> </head> <body> <?php // Create a fixed-size array with 3 elements $fixedArray = new SplFixedArray(3); // Assign values to the fixed array $fixedArray[0] = "apple"; $fixedArray[1] = "banana"; $fixedArray[2] = "orange"; // Accessing and displaying elements of the fixed array echo "<h2>Fruits:</h2>"; echo "<ul>"; for ($i = 0; $i < $fixedArray->getSize(); $i++) { echo "<li>$fixedArray[$i]</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
The resulting HTML page will display a list of fruits:
Fruits:
– apple
– banana
– orange
Here’s the code for the application:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Information Form</title> </head> <body> <?php // Initialize an empty associative array to store information $Info = []; // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] === "POST") { // Retrieve and store input in the associative array $Info["name"] = $_POST["name"]; $Info["age"] = $_POST["age"]; $Info["city"] = $_POST["city"]; } ?> <!-- Information Form --> <h2> Information Form</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> <label for="name">Name:</label> <input type="text" name="name" required><br> <label for="age">Age:</label> <input type="number" name="age" required><br> <label for="city">City:</label> <input type="text" name="city" required><br> <input type="submit" value="Submit"> </form> <?php // Display information in a table if submitted if ($_SERVER["REQUEST_METHOD"] === "POST") { echo "<h2> Information:</h2>"; echo "<table border='1'>"; foreach ($Info as $key => $value) { echo "<tr>"; echo "<td><strong>$key:</strong></td>"; echo "<td>$value</td>"; echo "</tr>"; } echo "</table>"; } ?> </body> </html>
Explanation:
This is a simple example to illustrate how PHP can be used to handle input and display information. You can expand and customize this application based on your specific requirements.
Here’s a quiz about PHP arrays. Each question has multiple-choice answers.
a. Store only strings
b. Store a single value
c. Store and manipulate collections of data
d. Execute mathematical operations
a. $array = {1, 2, 3};
b. $array = [1, 2, 3];
c. $array = array(1, 2, 3);
d. $array = array{1, 2, 3};
a. 0
b. 1
c. 2
d. The index is not applicable.
a. Indexed array
b. Associative array
c. Multidimensional array
d. Specialized array
a. $array[0];
b. $array{“key”};
c. $array[“key”];
d. $array(0);
a. An array that can only store integers
b. An array with only one element
c. An array containing other arrays
d. An array with a fixed size
a. array()
b. SplFixedArray()
c. new Array()
d. createFixedArray()
a. $array[0];
b. $array{“key”};
c. $array[“key”];
d. $array[0][0];
a. if
b. while
c. for
d. switch
a. To create arrays
b. To iterate through the elements of an array
c. To perform mathematical operations
d. To check conditions
a. array_count()
b. count_array()
c. array_size()
d. count()
a. Create HTML elements
b. Prevent potential XSS attacks
c. Display images
d. Format text
a. Server’s IP address
b. Server’s operating system
c. The request method used (GET or POST)
d. Server’s current time
a. isset($variable)
b. empty($variable)
c. check($variable)
d. validate($variable)
a. $array = [“key” => “value”];
b. $array = array(“key” => “value”);
c. $array = [“key”, “value”];
d. $array = array(“key”, => “value”);
1-c, 2. b, 3. a, 4. b, 5. c, 6. c, 7. b, 8. d, 9. c, 10. b, 11. d, 12. b, 13. c, 14. a, 15. c