PHP Change Array Element

In this chapter you will learn:

  1. How to change an element in an array
  2. Syntax to change array element
  3. Example - Change array element by index
  4. Example - Add to the last element
  5. Example - Append to the array end

Description

We can change values using the same techniques, [].

Syntax

To change indexed array.

$arrayName[0] = newValue
$arrayName[1] = newValue

To change associative arrays


$arrayName["key0"] = newValue
$arrayName["key1"] = newValue

Example 1

The following code changes the value of the third element in an indexed array from "CSS" to "Python".


<?PHP/*from  j a  va 2 s . com*/
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$authors[2] = "Python";   
var_dump($authors); 
?>

The code above generates the following result.

Example 3

What if you wanted to add a fifth author? You can just create a new element with an index of 4, as follows:


<?PHP//from  j  a v a 2 s .c  o  m
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$authors[4] = "Ruby";   
var_dump($authors); 
?>

The code above generates the following result.

Example 4

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


<?PHP/* j ava  2s .  co m*/
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$authors[] = "Ruby";   
var_dump($authors); 
?>

The code above generates the following result.

When you do this, PHP knows that you want to add a new element to the end of the array, and it automatically assigns the next available index to the element.

Next chapter...

What you will learn in the next chapter:

  1. How to create array using square bracket
  2. Syntax to create array using square bracket
  3. Example - create array using square bracket
  4. Example - clear array first and then create array using square bracket
  5. Example - create associative array using square bracket
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array