Using strlen() with arrays instead of strings

213 views Asked by At

I want to use strlen() to compare the length of two arrays. If the length of one array is greater than the other, then do something.

Unfortunately, I noticed that strlen() only works with strings? How can I make it work with arrays?

My code:

    $array1 = array(
        'Hello World',
        'Hello World',
        'Hello World',
        'Hello World',
        'Hello World'
    );

    $array2 = array(
        'Hello World',
        'Hello World'
    );


if (strlen($array1) > strlen($array2)) {

    echo 'It works you fool!';

}
2

There are 2 answers

0
James On BEST ANSWER

How can I make it work with arrays?

PHP manual for strlen():

strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

You can't really.

Is there some reason why you "want" to do this?
There is a perfectly good function to achieve what you want - count():

count — Count all elements in an array, or something in an object

if (strlen($array1) > strlen($array2))
  {
    echo 'It works you fool!';
  }

Don't try to work PHP functions to suit your needs in scenarios they are not designed for.
Especially when there is (almost always likely) a perfectly good function which already suits your needs.

Future changes could make your "hack" no longer work, and also using the correct function means you will likely benefit from PHP ensuring accuracy, stability, speed, etc etc.

Hacking around often causes headaches, even if not now, in the future.

3
MH2K9 On

To get array length you should use count().

if (count($array1) > count($array2)) {
    echo 'It works you fool!';
}