creating and modifying arrays in PHP

mroh

MROH

Posted on June 22, 2023

creating and modifying arrays in PHP

Arrays in a PHP Script allow for the organization of data. They can contain other arrays within them. Providing flexibility. There are various techniques available to create and modify arrays. An example of a 2 dimensional indexed array is shown below.

screenshot showing how to create a 2-dimensional indexed array in PHP

In this illustration, the array named $onyango is created with inner arrays representing rows and the values inside them representing each element of the row.
To access specific elements. We use the index of both the outer and inner arrays by using square brackets. For example. $onyango[0][0] accesses the element in the first row and first column. Which is 1. Similarly. $onyango[1][2] accesses the element in the second row and third column, which is 6, and $onyango[2][1] accesses the element in the third row and second column, which is 8.

b)
Associative arrays can be created and accessed by using key-value pairs as shown below.

a screenshot showing how to create and access elements in an associative array in PHP

In the illustration above we create an associative array called $user. We use descriptive keys like “name”, “age”, and “email” to associate values with specific keys instead of numeric indices.
To access elements of an associative array we use matching keys within square brackets ([])
For example, $user["name"] accesses the value associated with the "name" key, which is "Onyango Felix". Similarly, $user["age"] retrieves the value associated with the "age" key, which is 4, and $user["email"] retrieves the value associated with the "email" key, which is "felixo@gmail.com"
Associative arrays can be modified by assigning new values to specific keys as shown bellow

a screenshot showing how to modify the elements of an associative array in PHP

In the above illustration, we modified the value associated with the “age” key by assigning the new value of 30 to $user[age]. After modifying it will return 30.

💖 💪 🙅 🚩
mroh
MROH

Posted on June 22, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related