PHP - check if array includes value and return value if true I developed the function array_includes which checks if an array contains a value and returns it. I would like to know if there is already such a function which is more efficient or how I can make the function more efficient.

&lt;?php
$params = "colorgroup-b;test;abc";
$paramsArr = explode(";", $params);

var_dump(array_includes("colorgroup", $paramsArr));  //outputs: colorgroup-b

function array_includes($needle, $arr)
{       
    foreach($arr as $param) {
        if (strpos($param, $needle) !== false) {
            return $param;
        }
    }
    return false;
}
Your function checks if an array contains a string that contains your given $needle. No, there's no such function in PHP yet. The in_array() function does something else.

You could make your function more efficient if you include the explode() inside the function, like this:

function find_parameters($needle, $parameterStr)
{       
    if (strpos($parameterStr, $needle) !== false) {
        $result = [];
        foreach(explode(";", $parameterStr) as $parameter) {
            if (strpos($parameter, $needle) !== false) {
                $result[] = $parameter;
            }
        }
        return $result;
    } 
    return false;
}


This function first checks whether the parameter string actually does contain the needle. It can quickly return false when it doesn't. If the needle is present it does what your code does, with the exception that it returns an array. This is done so that it can return multiple results. Suppose your parameter string looks like this:

$params = "colorgroup-a;colorgroup-b;test;abc";


and you test this:

var_dump(find_parameters("colorgroup", $paramsArr));


Then it will not return only colorgroup-a, like your function, but it will return an array with colorgroup-a and colorgroup-b.

So this new function is more efficient, when there are no matching parameters, and it is more correct in that it finds all the parameters.

Yes, it is longer, but shortness of code should not be the main aim when writing code. The use of regular expressions is also very popular for these kind of tasks, and it would result in less code. But the engine behind regular expressions is complex, and would make the code a lot less efficient.