Daniel Tonon Daniel Tonon - 6 months ago 23
PHP Question

Check if PHP array contains a non-specfic string

This question is not me trying to find a specific string of characters inside an array. I'd like to know the simplest way to check if a string exists in an array. Example:

[1,2,3] // this does NOT contain a string
[1,'two',3] // this DOES contain a string


The best way I can think of is looping through all the array items and running is_string() on each of them like this.

$array = [1,'two',3];
$hasString = false;

foreach($array as $item){
if (is_string($item)){
$hasString = true;
}
}


This works but feels clunky. Is there a better way to do it that doesn't require looping through the array like this or is this as good as it gets?

Answer

You can use array_filter to check too:

<?php
function checkString($arr) {
    if (count(array_filter($arr, 'is_string'))) {
        return "Array has string";
    } else {
        return "Array hasn't any strings";
    }
}

echo checkString([1,'two',3]);
echo "<br/>";
echo checkString([1,2,3]);

Result:

Array has string
Array hasn't any strings

Your Eval

Comments