w3resource

PHP Exercises: Mutate the original array to filter out the values specified

PHP: Exercise-88 with Solution

Write a PHP program to mutate the original array to filter out the values specified.

Sample Solution:

PHP Code:

<?php
// Licence: https://bit.ly/2CFA5XY

// Function definition for 'pull' that takes an array reference and variable number of parameters as input
function pull(&$items, ...$params)
{
    // Use 'array_diff' to remove elements specified by the parameters from the array
    // Use 'array_values' to reindex the array after removal
    $items = array_values(array_diff($items, $params));

    // Return the modified array
    return $items;
}

// Initialize an array '$items' with repeated values
$items = ['a', 'b', 'c', 'a', 'b', 'c'];

// Call 'pull' with the array and specified values to be removed, then display the result using 'print_r'
print_r(pull($items, 'a', 'c'));

?>

Sample Output:

Array
(
    [0] => b
    [1] => b
)

Flowchart:

Flowchart: Mutate the original array to filter out the values specified.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to retrieve all of the values for a given key.
Next: Write a PHP program to filter the collection using the given callback.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.