Arrays
As a PHP developer working with arrays, here are some key points to consider:
- Specifying Array: Arrays can be specified using the
array()
function or square brackets[]
. For example:
phpCopy code$numbers = array(1, 2, 3);
$fruits = ['apple', 'banana', 'orange'];
- Accessing Array Elements: You can access array elements by their index or key. For indexed arrays, the index starts from 0. For associative arrays, you use the specified keys. For example:
phpCopy codeecho $numbers[1]; // Output: 2
echo $fruits[0]; // Output: apple
- Creating/Modifying Array: You can add, modify, or remove elements in an array using various methods. For example:
phpCopy code$numbers[] = 4; // Add element at the end
$fruits[1] = 'grape'; // Modify element
$fruits[] = 'watermelon'; // Add element at the end
unset($numbers[0]); // Remove element by index
unset($fruits['banana']); // Remove element by key
- Reading Array Values: You can loop through an array to read its values using loops like
foreach
,for
, orwhile
. For example:
phpCopy codeforeach ($fruits as $fruit) {
echo $fruit . ' ';
}
// Output: apple grape orange watermelon
- Removing Array Values: To remove elements from an array, you can use functions like
unset()
orarray_splice()
. For example:
phpCopy codeunset($fruits[1]); // Remove element by index
$removed = array_splice($fruits, 1, 2); // Remove elements starting from index 1 and remove 2 elements
- Array Traversal: You can traverse through an array using loops and perform operations on each element. For example:
phpCopy codeforeach ($numbers as $index => $value) {
echo "Element at index $index is $value\n";
}
- Useful PHP Array Functions: PHP provides various built-in functions to work with arrays. Some commonly used ones include:
count()
– Returns the number of elements in an array.sort()
– Sorts an indexed array in ascending order.rsort()
– Sorts an indexed array in descending order.array_push()
– Adds one or more elements to the end of an array.array_pop()
– Removes and returns the last element of an array.array_merge()
– Merges two or more arrays.array_keys()
– Returns all the keys of an array.array_values()
– Returns all the values of an array.
These are just a few examples of what you can do with arrays in PHP. PHP’s extensive array functions provide a wide range of options to manipulate and process array data.
Apply for PHP Certification!
https://www.vskills.in/certification/certified-php-developer