Reputation: 11
How can i delete an element from an array without using built-in functions in php ? But php doesn't have any keyword like delete or remove in it. can anyone help me ?
Upvotes: 0
Views: 463
Reputation: 85
Okay so from what I can see there is no logical way to do this and why do you want to do this? PHP was built with these functions for a reason and that's why we all use them.
I recommend you use the following
unset()
Function to Delete an Element From an Array in PHParray_splice()
Function to Delete an Element From an Array in PHParray_diff()
Function to Delete an Element From an
Array in PHPunset()
<?php
//Declare the array
$flowers = array(
"Rose",
"Lili",
"Jasmine",
"Hibiscus",
"Tulip",
"Sun Flower",
"Daffodil",
"Daisy");
unset($flowers[1]);
echo "The array is:\n";
print_r($flowers);
?>
This function can delete one value at a time. The name of the array along with the element index ($flowers[1]) is passed as a parameter. This function does not change the index values. The index values remain the same as they were before.
array_splice()
<?php
//Declare the array
$flowers = array(
"Rose",
"Lili",
"Jasmine",
"Hibiscus",
"Tulip",
"Sun Flower",
"Daffodil",
"Daisy");
array_splice($flowers, 4, 3);
echo "The array is:\n";
print_r($flowers);
?>
The array $flowers is passed as a parameter to this function along with the starting index 4 and the number of elements we want to delete-3. In this way, we can delete multiple elements from an array.
array_diff()
<?php
//Declare the array
$flowers = array(
"Rose",
"Lili",
"Jasmine",
"Hibiscus",
"Tulip",
"Sun Flower",
"Daffodil",
"Daisy");
$flowers = array_diff($flowers, array("Rose","Lili"));
echo "The array is:\n";
print_r($flowers);
?>
Here, the first array that we have passed is $flowers and the second array contains the elements that we want to delete from $flowers. This function does not change the indexes of the elements of the array.
Upvotes: 1