PHP Change Array Element

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// ww w.  j  a v a 2 s .  co m
$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//  w w w.ja  v  a2 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/* www  . j a  v  a  2s  . com*/
$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.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone