0

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?

3
  • 3
    Well you have to check element by element until you find a string, or not, to tell if there is a string in the array. So the only thing you could change is that you break; your loop in your code if you find a string so you can stop as soon as possible. Commented May 12, 2016 at 10:46
  • array_walk but it's really the same in the end. Commented May 12, 2016 at 10:53
  • "or is this as good as it gets" - good enough if break is used and the array has large amount of values Commented May 12, 2016 at 10:56

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, that's more like what I was after. A 1 line check to see if a string exists or not. I saved it to a variable in my code to make it easier to understand and re-use: $arrayHasString = count(array_filter($array, 'is_string'));
I might turn it into a function actually for even better re-use. :)
function array_has_string($array){ return count(array_filter($array, 'is_string')); }
then it will return the number if there are more than one string in the array not true or false. Just handle that before returning
This returns booleen now function array_has_string($array){ return count(array_filter($array, 'is_string')) ? true : false; }
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.