Introduction:
Explore the fundamentals of indexed arrays in PHP with our comprehensive lesson. Discover how to create, access, modify, and loop through indexed arrays. Enhance your understanding of PHP array operations with practical examples and explanations.
In PHP, an indexed array is a type of array where each element is assigned a numerical index. The index starts from 0 for the first element, 1 for the second element, and so on. Indexed arrays are sometimes referred to as numeric arrays because the keys are integers.
Here’s a basic example of an indexed array in PHP:
<?php // Creating an indexed array $colors = array("Red", "Green", "Blue"); // Accessing elements using index echo $colors[0]; // Output: Red echo $colors[1]; // Output: Green echo $colors[2]; // Output: Blue ?>
You can also create indexed arrays using the [] shorthand syntax introduced in PHP 5.4:
<?php // Creating an indexed array using shorthand syntax $colors = ["Red", "Green", "Blue"]; // Accessing elements using index echo $colors[0]; // Output: Red echo $colors[1]; // Output: Green echo $colors[2]; // Output: Blue ?>
Indexed arrays in PHP can be useful for storing and accessing data in a sequential manner.
You can perform various operations on indexed arrays, such as adding elements, removing elements, and iterating through the array using loops.
Here are some examples of common operations with indexed arrays:
Adding Elements:
<?php $colors[] = "Yellow"; // Adds "Yellow" to the end of the array $colors[3] = "Orange"; // Adds "Orange" at index 3 ?>
Removing Elements:
<?php unset($colors[1]); // Removes the element at index 1 ?>
Iterating through the Array:
<?php foreach ($colors as $color) { echo $color . ' '; } // Output: Red Green Blue Yellow Orange ?>
Indexed arrays are versatile and widely used in PHP for handling lists of data or sequences of items.
complete example in html with explanation
Let’s create a simple HTML file with a PHP script that uses an indexed array to store and display a list of colors. In this example, we’ll create an array of colors, add a new color, and then display the colors using a loop.
Create a file named index.php with the following content:
<!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 // Creating an indexed array $colors = ["Red", "Green", "Blue"]; // Adding a new color to the array $colors[] = "Yellow"; // Displaying the array using a loop echo "<p>List of Colors:</p>"; echo "<ul>"; foreach ($colors as $color) { echo "<li>$color</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
HTML Structure: The HTML structure is standard, with the addition of a title and a body.
PHP Code Block: The PHP code block is embedded within the HTML file using <?php ?> tags. Inside this block:
An indexed array named $colors is created with initial values “Red”, “Green”, and “Blue”.
A new color, “Yellow”, is added to the array using the shorthand syntax $colors[].
A loop (foreach) is used to iterate through the array, and each color is displayed as a list item.
Output: The output will be an HTML page that displays a list of colors:
List of Colors:
– Red
– Green
– Blue
– Yellow
You can save this code in a file with a .php extension (e.g., index.php) and run it on a web server with PHP support. When you access the file through a web browser, you should see the list of colors displayed on the web page.
To access indexed arrays in PHP, you use square brackets [] with the index of the element you want to access.
Here’s a complete code example with explanations:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Accessing Indexed Arrays</title> </head> <body> <?php // Creating an indexed array $colors = ["Red", "Green", "Blue"]; // Accessing elements using index echo "<p>Accessing Indexed Array Elements:</p>"; echo "<ul>"; echo "<li>Element at index 0: " . $colors[0] . "</li>"; // Output: Red echo "<li>Element at index 1: " . $colors[1] . "</li>"; // Output: Green echo "<li>Element at index 2: " . $colors[2] . "</li>"; // Output: Blue echo "</ul>"; ?> </body> </html>
Explanation:
HTML Structure: The HTML structure is standard, with the addition of a title and a body.
PHP Code Block: The PHP code block is embedded within the HTML file using <?php ?> tags. Inside this block:
An indexed array named $colors is created with initial values “Red”, “Green”, and “Blue”.
Accessing Elements: The echo statements within the HTML body are used to display information about accessing elements in the indexed array:
echo “<li>Element at index 0: ” . $colors[0] . “</li>”; accesses and displays the element at index 0 (Output: Red).
echo “<li>Element at index 1: ” . $colors[1] . “</li>”; accesses and displays the element at index 1 (Output: Green).
echo “<li>Element at index 2: ” . $colors[2] . “</li>”; accesses and displays the element at index 2 (Output: Blue).
Output: The output will be an HTML page that displays information about accessing indexed array elements:
Accessing Indexed Array Elements:
– Element at index 0: Red
– Element at index 1: Green
– Element at index 2: Blue
You can save this code in a file with a .php extension (e.g., index.php) and run it on a web server with PHP support. When you access the file through a web browser, you should see the information about accessing indexed array elements displayed on the web page.
To change the value of an array item in PHP, you can simply assign a new value to the corresponding index of the array.
Here’s an example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Changing Array Item Value</title> </head> <body> <?php // Creating an indexed array $colors = ["Red", "Green", "Blue"]; // Displaying the original array echo "<p>Original Array:</p>"; echo "<ul>"; foreach ($colors as $color) { echo "<li>$color</li>"; } echo "</ul>"; // Changing the value of an array item $colors[1] = "Yellow"; // Displaying the modified array echo "<p>Modified Array:</p>"; echo "<ul>"; foreach ($colors as $color) { echo "<li>$color</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
HTML Structure: The HTML structure is standard, with the addition of a title and a body.
PHP Code Block: The PHP code block is embedded within the HTML file using <?php ?> tags.
Inside this block:
An indexed array named $colors is created with initial values “Red”, “Green”, and “Blue”.
Displaying Original Array: The code uses a loop to display the original array values.
Changing Array Item Value: The line $colors[1] = “Yellow”; changes the value of the array item at index 1 to “Yellow”.
Displaying Modified Array: The code uses another loop to display the modified array values after changing the value.
Output: The output will be an HTML page that displays the original array followed by the modified array:
Original Array:
– Red
– Green
– Blue
Modified Array:
– Red
– Yellow
– Blue
You can save this code in a file with a .php extension (e.g., index.php) and run it on a web server with PHP support. When you access the file through a web browser, you should see the original and modified array values displayed on the web page.
To loop through an indexed array in PHP, you can use different types of loops. The most common loop used for this purpose is the foreach loop.
Here’s an example demonstrating how to loop through an indexed array using foreach:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Looping Through Indexed Array</title> </head> <body> <?php // Creating an indexed array $colors = ["Red", "Green", "Blue", "Yellow"]; // Using foreach to loop through the array echo "<p>Looping Through Indexed Array:</p>"; echo "<ul>"; foreach ($colors as $color) { echo "<li>$color</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
HTML Structure: The HTML structure is standard, with the addition of a title and a body.
PHP Code Block: The PHP code block is embedded within the HTML file using <?php ?> tags.
Inside this block:
An indexed array named $colors is created with values “Red”, “Green”, “Blue”, and “Yellow”.
Using foreach Loop: The foreach loop is used to iterate through each element in the indexed array. The syntax is foreach ($array as $value), where $array is the array being looped through, and $value is the current element in the iteration.
Displaying Array Elements: Inside the loop, each array element is displayed as a list item.
Output: The output will be an HTML page that displays the elements of the indexed array:
Looping Through Indexed Array:
– Red
– Green
– Blue
– Yellow
You can save this code in a file with a .php extension (e.g., index.php) and run it on a web server with PHP support. When you access the file through a web browser, you should see the elements of the indexed array displayed on the web page.
Create a file named color-app.php with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Color Application</title> </head> <body> <?php // Initialize the colors array $colors = []; // Check if the form is submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Get the color input from the form $newColor = $_POST['color']; // Validate and add the new color to the array if (!empty($newColor)) { $colors[] = $newColor; } } // Display the form to add a new color echo "<form method='post'>"; echo "<label for='color'>Add a Color:</label>"; echo "<input type='text' name='color' id='color' required>"; echo "<button type='submit'>Add Color</button>"; echo "</form>"; // Display the list of colors using a foreach loop echo "<p>List of Colors:</p>"; echo "<ul>"; foreach ($colors as $color) { echo "<li>$color</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
HTML Structure: The HTML structure includes a title, body, and a form for adding colors.
PHP Code Block: The PHP code block is embedded within the HTML file using <?php ?> tags.
Inside this block:
An indexed array named $colors is initialized to store the colors.
The code checks if the form has been submitted ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) and processes the submitted color if it is not empty.
Form Handling: The form includes an input field for adding a color. When the form is submitted, the entered color is added to the $colors array.
Displaying Form and Colors: The form is displayed to allow s to input a new color. The list of colors is then displayed using a foreach loop.
Output: The output will be an HTML page that allows s to add colors to a list, and the list is dynamically updated with the entered colors.
Save this code in a file with a .php extension (e.g., color-app.php) and run it on a web server with PHP support. Access the file through a web browser, and you should see the color input form and the list of colors on the web page. s can add new colors, and the list will be updated accordingly.
Here’s a quiz about PHP indexed arrays:
A. An array with named keys
B. An array with numerical keys
C. An array with mixed data types
D. An array with associative keys
A. $colors = (“Red”, “Green”, “Blue”);
B. $colors = array(“Red”, “Green”, “Blue”);
C. $colors = {“Red”, “Green”, “Blue”};
D. $colors = [1 => “Red”, 2 => “Green”, 3 => “Blue”];
A. $colors[2];
B. $colors{“2”};
C. $colors->get(2);
D. $colors->access(2);
A. while
B. for
C. foreach
D. do-while
A. $colors->add(“Yellow”);
B. $colors[4] = “Yellow”;
C. $colors->append(“Yellow”);
D. $colors[] = “Yellow”;
A. unset($colors[3]);
B. remove($colors, 3);
C. $colors->remove(3);
D. $colors->unset(3);
A. sizeOf()
B. count()
C. length()
D. elements()
A. Removes the last element
B. Adds a new element at the beginning
C. Adds a new element at the end
D. Creates a new array
A. $colors[1] = “Orange”;
B. $colors{“1”} = “Orange”;
C. $colors->change(1, “Orange”);
D. $colors->set(1, “Orange”);
A. To create a new array
B. To access elements by index
C. To iterate through each element in an array
D. To remove elements from an array
Answers:
1-B, 2. B, 3. A, 4. C, 5. D, 6. A, 7. B, 8. C, 9. A, 10. C