[vc_row][vc_column][vc_column_text]
How to delete an element from an array in PHP
There are many different ways to delete an element from an array.
We are discussing 2 ways
unset()
array_splice()
- If you want to delete an element from array.
The unset() function is used to delete element from the array. But the unset() not change the array keys or not reindex.
For example:
Array (
[0] => ‘Apple’
[1] => ‘Ball’
[2] => ‘Cat’
[3] => ‘Dog’
)
You want to delete element no 2
<?php
$arr = array(‘Apple’, ‘Ball’, ‘Cat’, ‘Dog’);
unset($arr[2]);
print_r($arr);
?>
Output:
Array (
[0] => ‘Apple’
[1] => ‘Ball’
[3] => ‘Dog’
)
- If you delete element with reindexing you can use array_splice()
The array_splice () function is used to delete element from the array. And after deleting element reindex the array
For example:
Array (
[0] => ‘Apple’
[1] => ‘Ball’
[2] => ‘Cat’
[3] => ‘Dog’
)
You want to delete element no 2
<?php
$arr = array(‘Apple’, ‘Ball’, ‘Cat’, ‘Dog’);
unset($arr[2]);
print_r($arr);
?>
Output:
Array (
[0] => ‘Apple’
[1] => ‘Ball’
[2] => ‘Dog’
)
[/vc_column_text][/vc_column][/vc_row]