PHP Change Array Element
In this chapter you will learn:
- How to change an element in an array
- Syntax to change array element
- Example - Change array element by index
- Example - Add to the last element
- 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:
- How to create array using square bracket
- Syntax to create array using square bracket
- Example - create array using square bracket
- Example - clear array first and then create array using square bracket
- Example - create associative array using square bracket