Arrays

Arrays

As a PHP developer working with arrays, here are some key points to consider:

  1. 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'];
  1. 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
  1. 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
  1. Reading Array Values: You can loop through an array to read its values using loops like foreach, for, or while. For example:
phpCopy codeforeach ($fruits as $fruit) {
    echo $fruit . ' ';
}
// Output: apple grape orange watermelon
  1. Removing Array Values: To remove elements from an array, you can use functions like unset() or array_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
  1. 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";
}
  1. 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

Back to Tutorials

Data storage in Android
The Break and Continue Statement

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?