PHP - Changing Array Elements


You can change values in array.

For example, the following code changes the value of the third element in an indexed array from "C" to "M" :

$authors = array("A","B","C","D");
$authors[2] ="M";

To add a fifth author, create a new element with an index of 4, as follows:

$authors = array("A","B","C","D");
$authors[4] ="O";

There's an even easier way to add a new element to an array - simply use square brackets with no index:

$authors = array("A","B","C","D");
$authors[] ="O";

You can create an array by creating its elements using the square bracket syntax.

The following three examples all produce exactly the same array:

// Creating an array using the array() construct
$authors1 = array("A","B","C","D");

// Creating the same array using [] and numeric indices
$authors2[0] ="A";
$authors2[1] ="B";
$authors2[2] ="C";
$authors2[3] ="D";

// Creating the same array using the empty [] syntax
$authors3[] ="A";
$authors3[] ="B";
$authors3[] ="C";
$authors3[] ="D";

However, just as with regular variables, you should make sure your arrays are initialized properly first.

In the second and third examples, if the $authors2 or $authors3 array variables already existed and contained other elements, the final arrays might end up containing more than just the four elements you assigned.

Always initialize your array variables when you first create them, even if you're not creating any array elements at that point.

You can do this easily by using the array() construct with an empty list:

$authors = array();

This creates an array with no elements (an empty array).

You can then go ahead and add elements later:

$authors[] ="A";
$authors[] ="B";
$authors[] ="C";
$authors[] ="D";

You can add and change elements of associative arrays using square bracket syntax.

Here an associative array is populated in two ways: first using the array() construct, and second using the square bracket syntax:

// Creating an associative array using the array() construct
$myBook = array("title" => "Java",
                "author" => "John A",
                "pubYear" =>  2018);

// Creating the same array using [] syntax
$myBook = array();
$myBook["title"] ="Java";
$myBook["author"] ="John A";
$myBook["pubYear"] = 2018;

Changing elements of associative arrays works in a similar fashion to indexed arrays:

$myBook["title"] ="Javascript";
$myBook["pubYear"] = 2017;

Related Topic