In PHP, an array is a variable that can hold multiple values of any data type.
To create an array, you can use the array() function or the shorthand syntax []. Here are examples of creating arrays:
“`php
// Using array() function
$fruits = array(“apple”, “banana”, “orange”);
// Using shorthand syntax
$fruits = [“apple”, “banana”, “orange”];
“`
To access values in an array, you can use the index of the element. Array indices start from 0. Here are examples of accessing array values:
“`php
echo $fruits[0]; // Output: apple
echo $fruits[1]; // Output: banana
echo $fruits[2]; // Output: orange
“`
To add elements to an array, you can use the [] operator with a new index or use the array_push() function. Here are examples of adding elements to an array:
“`php
$fruits[] = “mango”; // Adds “mango” to the end of the array
$fruits[4] = “grape”; // Adds “grape” to index 4 of the array
array_push($fruits, “watermelon”); // Adds “watermelon” to the end of the array
“`
To remove elements from an array, you can use the unset() function. Here is an example of removing an element from an array:
“`php
unset($fruits[1]); // Removes the element at index 1 (banana)
“`
To check if an element exists in an array, you can use the in_array() function. Here is an example of checking if an element exists in an array:
“`php
if (in_array(“apple”, $fruits)) {
echo “Apple is in the array”;
} else {
echo “Apple is not in the array”;
}
“`
You can also use various array functions to manipulate arrays, such as array_pop(), array_shift(), array_slice(), array_merge(), etc. Additionally, you can iterate over an array using loops like foreach, for, or while.
Arrays in PHP can also have keys assigned to each element. These are called associative arrays. Here is an example of creating an associative array:
“`php
$student = array(
“name” => “John”,
“age” => 20,
“grade” => “A”
);
“`
To access values in an associative array, you can use the key of the element. Here is an example of accessing values in an associative array:
“`php
echo $student[“name”]; // Output: John
echo $student[“age”]; // Output: 20
echo $student[“grade”]; // Output: A
“`
You can combine both numerical and associative indices in a single array.
These are the basic operations you can perform on arrays in PHP. There are many more functions and methods available to manipulate arrays in PHP.