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.
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.
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
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.
Top comments (1)
Well done Henry for your first or second blog as a result of participating in my PHP mentorship sessions.
My suggestions are;-