PHP one-liner to check if any values in array is longer than 5

Viewed 88

I want to check if any values inside my PHP array is longer than 5 words, using one-liner / simple method.

Output should be a boolean indicating the result.

This is what I come up with:

$isAnyValueTooLong = count(array_filter($array, function ($var)
{
    return strlen($var) > 5;
})) > 0;

So it can be used like so:

$array = ["1234", "123456"]; // This should be fail

//$array = ["1234", "1", "123" ]; // This should be OK


$isAnyValueTooLong = count(array_filter($array, function ($var)
{
    return strlen($var) > 5;
})) > 0;

if($isAnyValueTooLong){
  echo "Error, one of the item is longer than 5";
} else {
  echo "Ok, no error";
}

However, my method is hard to read and complex. My question is, any one-liner to achieve the above requirement?

Performance is not of concern as it is just a simple report program. Thanks.

1 Answers

If you are using PHP 7.4, you can make use of arrow syntax. Since you're not concerned about the performance.

$hasLongString = in_array( true, array_map( fn ($e)=> strlen($e) > 5, $array));
  
  
$output = $hasLongString ? "Found Longer Keys" : "All Good";

OR

$output = in_array(true, array_map( fn($e)=> strlen($e) > 5, $array)) ? "Found Longer Keys" : "All Good";

Basically, I am looping through the $array to covert the elements to boolean and looking for a true/false in that.

If you want to go OG.

$hasLongString = in_array( true, array_map( function ($e) { return strlen($e) > 5; } , $array));
  
  
if($hasLongString) echo "Oops, found longer key";

Related