Remove all elements from array that do not start with a certain string

You can use the array_filter() function in PHP to remove all elements from an array that do not start with a certain string. The function takes two arguments: the array and a callback function that defines the filtering criteria.

Watch a course Learn object oriented PHP

Here's an example of how to use array_filter() to remove all elements from an array that do not start with the string "apple":

<?php 

$fruits = array("apple", "banana", "orange", "apple", "grape");

$filtered_fruits = array_filter($fruits, function($fruit) {
    return strpos($fruit, 'apple') === 0;
});

print_r($filtered_fruits);

The above code will output:

Array
(
    [0] => apple
    [3] => apple
)

It's filtering the array by checking if the element start with the string 'apple' using strpos() function and if it's true then it keep that element otherwise remove from array.