PHP Accessing and Updating Array Elements

In the last lesson you have learned how to create an array in PHP. PHP arrays are created using keys or indexes. So, accessing and updating array elements in PHP is also done by using the element key or its index.

Accessing Array Elements

You can pick the value of an array element by accessing it. The accessed element value can be stored in a variable and used for a calculation. Array element can be accessed by index or key.

The syntax for accessing an array element in PHP is

$var-Name=Array-Name[integer index | string key]

Array-name is name of an array you have already created. Integer Index or a string key must be passed to access an element enclosed in square parentheses. Index is passed when the array is created with index values. String key is passed when array is an associative array.

Using Element Index

$StuMarks=array(45, 67,34,42,77,21);

PHP array accessing

In this example the elements values and indexes are assigned this way

To access element at index 3, the following code is used

$marks=$StuMarks[3]; // $marks variable will get value stored at index 3 in $StuMarks array

Using String Keys

$StuMarks=array(“Sam”=>45, “Rob”=>67,”May”=>34,”Han”=>42,”Jon”=>77,”Pam”=>21);

In this example the elements values and keys are assigned in this way

PHP accessing array element by key

To access element with key value “Jon” the following code is used

$marks=$StuMarks[“Jon”]; // $marks variable will get the value assigned to string key “Jon”

Updating Array Elements

PHP arrays are updatable. You can change value of elements by assigning a new value. The older value will get replaced by new value. The syntax of updating an array element in PHP is  

Array-Name[integer index | string key]= $var-Name|Value

Array-name is name of an existing array. Integer Index or a string key must be passed to update an element, enclosed in square parentheses. Index is used when the array is created with index values. String key is used when array is an associative array.  $var-name is the name of the variable that you want to use to update the array element. You can also set the new value of an array element by using a constant like string or number.

Using Element Index

 To update value of 3rd element of the array in the above example

$marks=89

$StuMarks[3]= $marks;

You can see that in the figure the value  42 at index 3  is replaced by 89.

PHP array Update

Using Element string Key

 To update value of element identified by key “Jon” in the array in the above example

$marks=89

$StuMarks[“Jon”]= $marks;

You can see that in the figure the value at key ‘Jon’  is replaced by 89.

PHP-Array-Key-update

Read more about Accessing and Updating Array Elements in PHP at the official documentation