Detailed Guide on Arrays in PHP
1. Types of Arrays in PHP
- Indexed Array: Uses numeric indices.
Example: $colors = array("Red", "Green", "Blue");
- Associative Array: Uses named keys.
Example: $student = array("name" => "John", "age" => 21);
- Multidimensional Array: Array containing one or more arrays.
Example:
$marks = array(
"John" => array("Math" => 90, "Science" => 85),
"Jane" => array("Math" => 80, "Science" => 95)
);
2. Accessing Array Elements
- Indexed Array: Access using numeric index.
Example: echo $colors[0]; // Red
- Associative Array: Access using string keys.
Example: echo $student["name"]; // John
- Multidimensional Array:
Example: echo $marks["John"]["Math"]; // 90
3. Performing Array Operations
- Add Elements: array_push($array, "value");
Detailed Guide on Arrays in PHP
- Remove Last: array_pop($array);
- Merge Arrays: array_merge($array1, $array2);
- Slice: array_slice($array, 1, 2);
- Check Exists: in_array("value", $array);
Example:
$nums = array(1, 2, 3);
array_push($nums, 4); // Now: [1, 2, 3, 4]
4. Taking Array Inputs from User
Using HTML Form and PHP:
Form (HTML):
<form method="post">
<input type="text" name="data[]">
<input type="text" name="data[]">
<input type="submit">
</form>
Processing (PHP):
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['data'];
foreach ($data as $item) {
echo $item . "<br>";
5. Useful Array Functions
Detailed Guide on Arrays in PHP
- count($array): Get total elements.
- array_keys($array): Get all keys.
- array_values($array): Get all values.
- sort($array): Sort indexed array ascending.
- ksort($array): Sort associative array by key.
- asort($array): Sort associative array by value.
6. Best Practices and Tips
- Always check if a variable is an array using is_array().
- Use foreach for cleaner array looping.
- Associative arrays are best when data is key-value structured.
- Multidimensional arrays are useful for tabular data (like student marks).