简体   繁体   中英

PHP - why doesn't count() work like strlen() on a string?

A string is an array of characters, correct? If so, then why does count() not produce the same result as strlen() on a string?

Unless it is an object, count casts its argument to an array, and

  count((array) "example")
= count(array("example"))
= 1

A string is an array of characters in C, C++ and Java. In PHP, it is not. Remember that PHP is a very loose language, you can probobly get a character from a PHP string with the [] -selector, but it still dosn't make it an array.

count() counts the number of entries in an Array .

$test = array(1,2,3);
echo count($test);

Output: 3

Why would you want to use count() on a string when strlen() can do that? Are you not sure if your input is a string or an array ? Then use is_array() to check that.

How exactly a string is being handled internally by a specific programming language, must not necessarily mean you can handle it equally to therefore "related" data types. What you describe may be possible in plain C. However PHP is not C and so is not following the same characteristics.

Strings are just a series of charactes, and count only counts number of elements in an array.

using $string[$index]; its just a shortcut kinda of thing to help you find Nth character,

you could use count(explode('',$string)); which presumably is what strlen does

so lesson for today is

count == array length

strlen == string length

count gets the number of elements in an array, srtlen gets the length of a string. This is in the docs:

http://php.net/manual/en/function.strlen.php

count更多preferabaly用户的数组值计数strlen它只计算str中的char的数量.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM