Arrays are a crucial data structure in PHP, allowing you to store multiple values in a single variable. PHP offers various functions to manipulate arrays effectively. Here are some common ways to work with arrays:
Creating an Array:
You can create arrays using the array() function or the short array syntax [].
<?php
// Using array() function
$fruits1 = array("Apple", "Banana", "Orange");
var_dump($fruits1);
// Using short array syntax
$fruits2 = ["Apple", "Banana", "Orange"];
var_dump($fruits2);
Accessing Array Elements:
You can access array elements by referring to their index.
<?php
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Outputs: Apple
Adding Elements to an Array: Use array_push() or simply assign a value to a new index to add elements to an array.
<?php
$fruits = ["Apple", "Banana", "Orange"];
// Adding using array_push()
array_push($fruits, "Grapes");
// Adding using array index
$fruits[] = "Mango";
var_dump($fruits);
Removing Elements from an Array: You can remove elements from an array using unset() or array functions like array_pop() and array_shift().
<?php
$fruits = ["Apple", "Banana", "Orange"];
// Remove last element
array_pop($fruits);
// Remove first element
array_shift($fruits);
// Remove element by index
unset($fruits[1]); // Removes Banana
var_dump($fruits);
Iterating Over an Array: Loop through an array using foreach().
<?php
$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $fruit) {
echo $fruit;
}
Merging Arrays: Combine arrays using array_merge().
<?php
$fruits = ["Apple", "Banana", "Orange"];
$moreFruits = ["Pineapple", "Watermelon"];
$allFruits = array_merge($fruits, $moreFruits);
var_dump($allFruits);
Sorting Arrays: You can sort arrays with functions like sort(), rsort(), asort(), ksort(), etc.
<?php
$fruits = ["Apple", "Banana", "Orange"];
sort($fruits); // Sort in ascending order
var_dump($fruits);
You can run the code at https://onecompiler.com/php