How to use array_values() with array_splice() In PHP
To delete array elements by value using array_values() with array_splice() in PHP, find the key of the value, splice the array at that key, then reindex the array using array_values().
Example: In this example we declares an associative array, prints it, finds and removes a specified value (‘Java’), reindexes the array using array_values(), and then prints the modified array.
<?php
# Declaring an associative array
$arr = array(
'key1' => 'w3wiki',
'key2' => 'Python',
'key3' => 'Java',
);
# Printing original array
echo "Original Array: \n";
var_dump($arr);
# Declaring the value to delete
$val = 'Java';
# Finding the key on the basis of value
$key = array_search($val, $arr);
# If the value exists in the array, delete it
if ($key !== false) {
# Remove the element at the found key
unset($arr[$key]);
# Reindex the array
$arr = array_values($arr);
}
echo "<br><br>Modified Array: \n";
var_dump($arr);
?>
Output
Original Array: array(3) { ["key1"]=> string(13) "w3wiki" ["key2"]=> string(6) "Python" ["key3"]=> string(4) "Java" } <br><br>Modified Array: array(2) { [0]=> string(13) "Geek...
How to perform Array Delete by Value Not Key in PHP ?
An array is essentially a storage element for key-value pairs belonging to the same data type. If keys are specified explicitly, ids beginning from 0 as assigned to the values by the compiler on their own. Arrays allow a large variety of operations, like access, modification, and deletion upon the stored elements. The element positions are then adjusted accordingly.
Table of Content
- array_search() method
- array_diff() method
- Using array_values() with array_splice()
Contact Us