Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Adding and Removing Elements in Arrays | Arrays
Introduction to PHP
course content

Conteúdo do Curso

Introduction to PHP

Introduction to PHP

1. First Acquaintance
2. Variables and Data Types
3. Conditional Statements
4. Arrays
5. Loops

bookAdding and Removing Elements in Arrays

There are straightforward methods to add new elements to an array and remove existing ones. Let's explore these processes with examples.

Adding Elements to an Array


Adding elements to an array can be done using the [] operator to append to the end of the array or by specifying keys for new values.

Append to the end of an array:

php

main

copy
12345678910
<?php $array = []; // Initialize an empty array // Adding elements to the end of the array $array[] = "element 1"; $array[] = "element 2"; $array[] = "element 3"; print_r($array); ?>

In the example above, we initialize an empty array $array and then append three new lines to the end of the array using the [] operator.

Adding Elements with Specified Keys to Associative Arrays:

php

main

copy
12345678910
<?php $array = []; // Initialize an empty array // Adding elements with specified keys $array["key1"] = "value 1"; $array["key2"] = "value 2"; $array["key3"] = "value 3"; print_r($array); ?>

Here, we use strings "key1", "key2", and "key3" as keys for the values being added.

Removing Elements from an Array


To remove elements from an array in PHP, we use the unset() function for removing by index or key.

Removing by index:

php

main

copy
12345678
<?php $array = ["element 1", "element 2", "element 3"]; // Removing element at index 1 unset($array[1]); print_r($array); ?>

In this example, unset($array[1]); removes the element at index 1 (which is "element 2").

Removing by key:

php

main

copy
12345678
<?php $array = ["key1" => "value 1", "key2" => "value 2", "key3" => "value 3"]; // Removing element with key "key2" unset($array["key2"]); print_r($array); ?>

Here, unset($array["key2"]); removes the element with key "key2" (which is "value 2").

Using built-in PHP functions like unset(), and array_splice() provides a convenient and efficient way to manipulate arrays dynamically. These methods are essential for managing data structures in PHP applications.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 4
some-alt