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

Зміст курсу

Introduction to PHP

Introduction to PHP

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

Adding 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

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

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

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

Removing by key:

php

main

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.

Все було зрозуміло?

Секція 4. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt