PHP arrays are data structures used to store multiple values in a single variable. PHP arrays can hold different data types together and allow various operations to be performed on this data. Arrays are often very useful when working with datasets.
There are two types of arrays in PHP: indexed array and associative array (key-value array).
Indexed arrays are arrays that hold data in the form of an ordered list. Each element is associated with an index (number) and the sorting starts from 0.
$renkler = array("Kırmızı", "Mavi", "Yeşil");
echo $renkler[0]; // Kırmızı
In this example, the element with index 0 in the $renkler array is "Kırmızı".
Key-value arrays are arrays where each element is associated with a key. This allows data to be accessed in a more flexible and readable way.
$personel = array("ad" => "Ahmet", "soyad" => "Alkan", "yaş" => 28);
echo $personel["ad"]; // Ahmet
In this example, the $personel array has values associated with the keys "ad", "soyad", and "yaş".
Multidimensional arrays can be thought of as arrays of arrays. That is, there is more than one array within an array. These types of arrays are often used for more complex data structures.
$ogrenciler = array(
array("isim" => "Ali", "not" => 85),
array("isim" => "Ayşe", "not" => 90)
);
echo $ogrenciler[0]["isim"]; // Ali
In this example, there are arrays within the $ogrenciler array, each of which belongs to a student.
The array_push() function can be used to add elements to the array. This function adds one or more elements to the end of the array.
$renkler = array("Kırmızı", "Mavi");
array_push($renkler, "Yeşil");
print_r($renkler); // Kırmızı, Mavi, Yeşil
To add a new key and value to a key-value array, you can directly create a new key using the name of the array.
$personel = array("ad" => "Ahmet", "soyad" => "Yılmaz");
$personel["yaş"] = 30;
print_r($personel);
You can use functions such as array_pop() or unset() to remove elements from an array. While the array_pop() function removes the last element of the array, the unset() function completely removes a particular element from the array.
$renkler = array("Kırmızı", "Mavi", "Yeşil");
array_pop($renkler);
print_r($renkler); // Kırmızı, Mavi
//Removing Specific Element
$personel = array("ad" => "Ahmet", "soyad" => "Yılmaz", "yaş" => 30);
unset($personel["yaş"]);
print_r($personel); // Age element has been removed