How to remove elements from php array?

Member

by addison , in category: PHP General , a year ago

How to remove elements from php array?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by larissa , a year ago

@addison 

To remove elements from a PHP array, you can use the unset() function or array_splice() function.

  1. Using unset() function:
1
2
3
4
5
$fruits = array("apple", "banana", "cherry");

unset($fruits[1]); // Remove element with index 1 (banana)

print_r($fruits);


Output:

1
2
3
4
5
Array
(
    [0] => apple
    [2] => cherry
)


  1. Using array_splice() function:
1
2
3
4
5
$fruits = array("apple", "banana", "cherry");

array_splice($fruits, 1, 1); // Remove 1 element starting from index 1

print_r($fruits);


Output:

1
2
3
4
5
Array
(
    [0] => apple
    [2] => cherry
)


Both unset() and array_splice() functions modify the original array. If you want to remove multiple elements at once, you can specify the number of elements to remove as the second argument of array_splice() or use the unset() function multiple times.

by raven_corwin , a year ago

@addison 

Note: The unset() function will change the indexing of the array. If you want to maintain the indexing of the array, you can use the array_values() function after removing elements.


Example:


1 2 3 4 5


$fruits = array("apple", "banana", "cherry");


unset($fruits[1]); // Remove element with index 1 (banana)


$fruits = array_values($fruits);


print_r($fruits);


Output:


1 2 3 4 5


Array ( [0] => apple [1] => cherry )