PHP Tutorials

PHP Array Tutorial: Create, Access, and Update Arrays

Learn how to create, access, update, and remove PHP array elements with simple examples that make the basics easy to understand.

Serhat ALPASLAN3 min read

Contents

PHP

A PHP array lets you store data together with keys. To explain with an example, the word “Merhaba” is made up of 7 letters. Here the letter M is at index 0, the letter E at index 1, and so on. In a PHP array the indexes (indices) start at 0, so you need to pay special attention to this.

How Do You Create an Array?

There are 3 types of arrays in PHP.

  • Indexed Arrays
  • Associative Arrays
  • Multidimensional Arrays

We can create arrays in 2 ways.
Method 1

$arrayAdi= [deger1, deger2, deger3, ...];

Method 2

$arrayAdi= array(deger1, deger2, deger3, ...);

How Do You Access the Elements in an Array?

We can access the elements in an array in 2 ways. The first is by index number, and the other is by key value.

<?php

$dizi= ["Merhaba", 2.23, -53, "Dizi Örneği"];
echo $dizi[0];

?>

In the example above, the output returned will be “Merhaba”.

In the other method, the array elements must have a key value. We can only access them this way; otherwise you can access them by index number.

<?php
$dizi= [
    "Mesaj" => "Merhaba",
    "sayi" => 3.14,
    1 => -59870,
    2 => "Dizi Örneği"
];
echo $dizi["sayi"];

Let’s access the array values using a foreach loop;

<?php
$dizi= [
    "Mesaj" => "Merhaba",
    "sayi" => 33.124,
    1 => -592218730,
    2 => "Array dizi örneği"
];

foreach ($dizi as $key => $value) {
    echo $key ." - ".$value;
    echo "<br>";
}

How Do We Change Array Values?

Arrays are actually variables. When you want to change the values in an array, you need to know the element’s key or the array’s index number.

<?php

// Defining the array 
$dizi= ["Mesaj" => "Merhaba"];
echo $dizi["Mesaj"] . "<br>";

// Let's change the array value 
$arr["Mesaj"] = "Selam";
echo $dizi["Mesaj"];

?>

How Do You Remove an Element from an Array?

In PHP you can remove an element from an array with the unset() command.

<?php
$dizi = [
    "Mesaj" => "Merhaba",
    "Sayi" => 3.14,
    1 => -123456,
    2 => "Dizi örnegi"
];
echo $dizi["Mesaj"] . "<br>";

// Let's delete the element 
unset($dizi["Mesaj"]);
echo $dizi["Mesaj"] . "<br>";
?>

We can use the unset() call above in the same way to remove an entire array.

<?php

$dizi = [
    "Mesaj" => "Merhaba",
    "Sayi" => 3.14,
    1 => -123456,
    2 => "Dizi örnegi"
];
echo $dizi["Mesaj"] . "<br>";

// Let's remove the array
unset($dizi);
echo $dizi["Mesaj"] . "<br>";
?>

Share it if it helped

Write a comment