PHP Arrays

please click here for more wordpress cource

Arrays in PHP are a type of data structure that allows you to store multiple values of different data types in a single variable. PHP arrays can be indexed numerically or using associative keys.

Here are some examples of how to create and manipulate arrays in PHP:

Creating an indexed array:

$fruits = array("apple", "banana", "orange");

Creating an associative array:

$person = array("name" => "John", "age" => 30, "location" => "New York");

Accessing array elements:

echo $fruits[0]; // outputs "apple"
echo $person["name"]; // outputs "John"

Looping through an array:

foreach ($fruits as $fruit) {
  echo $fruit;
}

foreach ($person as $key => $value) {
  echo $key . ": " . $value;
}

Adding elements to an array:

$fruits[] = "grape";
$person["occupation"] = "teacher";

Removing elements from an array:

unset($fruits[1]);
unset($person["location"]);

Sorting an array:

sort($fruits); // sorts the array in ascending order rsort($fruits); // sorts the array in descending order ksort($person); // sorts the array by keys in ascending order

There are many other functions and methods available for manipulating arrays in PHP, including merging arrays, searching for elements, and filtering elements based on certain criteria.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *