Daniel Tonon
Daniel Tonon

Reputation: 10442

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?

Upvotes: 0

Views: 280

Answers (2)

Daniel Tonon
Daniel Tonon

Reputation: 10442

Since it is kind of a different answer to Thamilan's answer now, I'm posting the comment as an answer.

function array_has_string($array){
    return count(array_filter($array, 'is_string')) ? true : false;
}

$test_1 = array_has_string([1,'two',3]);

//$test_1 = true

$test_2 = array_has_string([1,2,3]);

//$test_2 = false

Upvotes: 0

Thamilhan
Thamilhan

Reputation: 13313

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

Upvotes: 2

Related Questions