Why Use of an Array?
- Dynamic Size: PHP arrays are dynamic, meaning you can add or remove elements without the need to declare a fixed size. This flexibility makes arrays suitable for handling varying amounts of data.
- Versatility: PHP arrays can store different data types within the same array. You can have a mix of strings, integers, floats, and even other arrays as elements within a single array.
- Indexed and Associative Arrays: PHP supports both indexed arrays (numeric keys) and associative arrays (string keys). This flexibility allows you to choose the most appropriate type based on your specific use case.
- Efficient Data Retrieval: PHP arrays provide fast and efficient data retrieval. You can quickly access an element using its key or index, making it suitable for scenarios where fast lookups are essential.
- Built-in Array Functions: PHP comes with a rich set of built-in array functions that make it easy to manipulate and process array data. Functions like count(), foreach(), array_map(), and array_filter() simplify common array operations.
- Array Iteration: PHP provides convenient ways to iterate through arrays, such as using foreach loops. This makes it easy to perform actions on each element of an array without dealing with explicit indexing.
- Passing Arrays to Functions: PHP allows you to pass arrays to functions, making it convenient to work with collections of data. Functions can receive arrays as arguments, enabling modular and reusable code.
- Serialization and Unserialization: PHP provides functions like serialize() and unserialize() that allow you to convert arrays into a string representation and vice versa. This is useful for storing arrays in databases or transferring them between different parts of an application.
- Sorting and Searching: PHP provides functions for sorting arrays (sort(), asort(), ksort(), etc.) and searching for specific values (in_array(), array_search(), etc.), making it easy to organize and retrieve data.
- JSON Representation: PHP arrays can be easily converted to JSON format using the json_encode() function. This is particularly useful for exchanging data between a PHP backend and a JavaScript frontend.
- Memory Efficiency: PHP arrays are implemented efficiently in terms of memory usage, making them suitable for handling large datasets without significant overhead.
- Numeric array/Indexed array − An array with a numeric index. Values are stored and accessed in linear fashion.
- Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
- Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices
Create an Array in PHP
In PHP, there are different ways to create an array, and the syntax can vary depending on whether you're creating a numerically indexed array or an associatively indexed array.
1.Numeric array/Indexed array :
- In PHP, the array() function is used to create a numerically indexed array: Syntax: array();
- An array with a numeric index is the Numeric array/Indexed array. Values are stored and accessed in linear fashion.
- These arrays can store numbers, strings and any object but their index will be represented by numbers.
- By default array index starts from zero.
- In an indexed or numeric array, the indexes are automatically assigned and start with 0 and the values can be any data type.
- “$variable_name…”
is the name of the variable
- “[n]”
is the access index number of the element
- “value”
is the value assigned to the array element.
$cars[1] = "BMW";
$cars[2] = "Toyota";
- Here, an array named $cars is created and initialized with three elements: "Volvo", "BMW", and "Toyota".
- echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; This line of code uses the echo statement to output a string. The string is constructed by concatenating various elements. Let's break it down to learn better:
- "I like ": A static string indicating the beginning of the sentence.
- $cars[0]: Accesses the first element of the $cars array, which is "Volvo".
- ", ": A static string used as a separator between the car names.
- $cars[1]: Accesses the second element of the $cars array, which is "BMW".
- " and ": A static string used before the last car name.
- $cars[2]: Accesses the third element of the $cars array, which is "Toyota".
- ".": A static string representing the end of the sentence.
$cars[1] = "BMW";
$cars[2] = "Toyota";
Traversing PHP Indexed
Array
"Traversing PHP Indexed Array" refers to the process of iterating through each element of an indexed array in PHP. Traversing allows you to access and manipulate each element of the array sequentially. Indexed arrays in PHP are collections of values where each value is associated with a numeric index, starting from 0.
There are several ways to traverse (or loop through) an indexed array in PHP. Here are a few common methods:
Case 1: Using for Loop:
$numbers = array(1, 2, 3, 4, 5);
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . " ";
}
Output:
1 2 3 4 5
Explanation:
- $numbers = array(1, 2, 3, 4, 5); : This line initializes an array named $numbers with the values 1, 2, 3, 4, and 5.
- for ($i = 0; $i < count($numbers); $i++) { echo $numbers[$i] . " "; }
- This for loop iterates through the array using an index ($i) starting from 0 and incrementing it until it reaches the count of elements in the array (count($numbers)). For each iteration, it prints the value of the array at the current index ($numbers[$i]) followed by a space.
- The result of the loop is that each element of the array is printed to the screen, separated by spaces.
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $number) {
echo $number . " ";
}
Output:
1 2 3 4 5
Explanation:
- $numbers = array(1, 2, 3, 4, 5); This line initializes an array named $numbers with the values 1, 2, 3, 4, and 5.
- foreach ($numbers as $number) { echo $number . " "; } This foreach loop iterates through each element of the array ($numbers) without the need for an explicit index. For each iteration, it assigns the current array element to the variable $number, and then it prints the value of $number followed by a space.
- The result of the loop is that each element of the array is printed to the screen, separated by spaces.
Case 3: Using while Loop:
$numbers = array(1, 2, 3, 4, 5);
$count = count($numbers);
$i = 0;
while ($i < $count) {
echo $numbers[$i] . " ";
$i++;
}
Output:
1 2 3 4 5
Explanation:
- $numbers = array(1, 2, 3, 4, 5); This line initializes an array named $numbers with the values 1, 2, 3, 4, and 5.
- Counting Array Elements: $count = count($numbers); The count() function is used to determine the number of elements in the array, and the result is stored in the variable $count.
- $i = 0; while ($i < $count) { echo $numbers[$i] . " "; $i++; } This while loop iterates through the array using an index ($i) starting from 0 and incrementing it until it reaches the count of elements in the array ($count). For each iteration, it prints the value of the array at the current index ($numbers[$i]) followed by a space.
- The result of the loop is that each element of the array is printed to the screen, separated by spaces.
In each of these examples, the array $numbers is traversed, and each element is echoed or processed in some way. The for, foreach, and while loops are commonly used for traversing arrays, and the choice of loop depends on the specific requirements of your code.
Traversing an array is a fundamental operation in programming, and it allows you to perform actions on each element of the array, such as printing them, performing calculations, or updating their values.
Example2:
- <?php
- $size=array(“Big”,”Medium”,”Short”);
- foreach($size as $s)
- {
- echo “Size is : $s<br/>”;
- } ?>
2)PHP Associative Array
- Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.
- An associative array in PHP is an array where each element is associated with a specific key instead of being accessed by a numerical index. In other words, you use meaningful keys to represent values in the array.
- In an associative array, the keys assigned to values can be arbitrary and user defined strings.
- In the Associative array, the array uses keys instead of index numbers.
- Associative array are also very useful when retrieving data from the database.
- The field names are used as id keys.
- To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
- Don't keep associative array inside double quote while printing otherwise it would not return any value.
- Keys and values are separated by =>.
- Each key-value pair is separated by a comma.
- The entire associative array is enclosed in parentheses or square brackets.
- You can use various data types as keys and values, including strings, numbers, and even other arrays. Keys must be unique within an associative array.
Generally By the help of PHP for each loop, we can easily traverse the elements of PHP associative array. There are several ways to traverse (or loop through) an Associative array in PHP. Here are a few common methods:
Case 1: Using for Loop:
- $person = array(
- Obtaining Keys with array_keys(): $keys = array_keys($person);
- Traversing the Array Using a for Loop:
- Output:The result of the loop is that each key-value pair from the associative array is printed to the screen, separated by a colon and a line break.This code demonstrates an alternative way to traverse an associative array using a for loop, although it's generally less common than using foreach. The foreach loop is often preferred for its simplicity and readability when working with associative arrays.
- An associative array named $person is created with three key-value pairs.
- The foreach loop is used to iterate through each key-value pair in the associative array.
- as $key => $value: For each iteration, the current key is assigned to the variable $key, and the corresponding value is assigned to the variable $value.
- Inside the loop, the echo statement prints the current key, a colon, the current value, and a line break (<br>).
- The result of the loop is that each key-value pair from the associative array is printed to the screen, separated by a colon and a line break.
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Case 1: Using while Loop:
- An associative array named $person is created with three key-value pairs.
- Get the First Key-Value Pair: list($key, $value) = each($person); The each() function is used to get the first key-value pair from the associative array. The list() function is then used to assign the key to $key and the value to $value.
- While Loop for Traversal:
- The while loop is used to iterate through the associative array until the internal array pointer reaches the end.
- The loop condition checks if the current key ($key) is not equal to null.
- Inside the loop, the key-value pair is echoed, and then each() is used again to get the next key-value pair.
- Output: The result of the loop is that each key-value pair from the associative array is printed to the screen, separated by a colon and a line break.
3. Multidimensional Arrays
- In PHP, a multidimensional array is an array that contains one or more arrays as its elements. These inner arrays can, in turn, contain other arrays, creating a nested or hierarchical structure. Multidimensional arrays are useful for representing and working with more complex data structures.
- PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array.
- A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.
- The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain array within itself and so on.
- PHP multidimensional array can be represented in the form of matrix which is represented by row * column.
- The advantage of multidimensional arrays is that they allow us to group related data together.
PHP - Two-dimensional Arrays
- The $students array is initialized using the short array syntax ([]).
- It is a two-dimensional array with three inner arrays, each representing a student's information.
- Each inner array represents a student.
Traversing the Multidimensional Array with foreach:
- Array Initialization:
- Display Setup:
- Foreach Loop for Display:
Inside the outer loop, a list item (<li>) is echoed for each student.
The inner foreach loop iterates through each value within the student's information array, echoing the values with a space between them.
- Closing Tags:
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
No comments:
Post a Comment