简体   繁体   中英

PHP function passing arguuments?

Now I am dealing with PHP but I`ve stucked with a strange issue: I am making a simple foo for string length:

function slen($str) {
  $len;
  for ( $len=0; $str[$len]; $len++ ) {
          /* while tehre is a symbol in $str continue counting, old C metnod */
   }
   return (int)$len;
}

it`s on as a code, and outputs the length but it booms with an PHP warning message : PHP Notice: Uninitialized string offset: 3 in /home/ilian/Desktop/SERVER/ex4.php on line 5 And on my line 5 is the for loop initialization. So I got that PHP might be confusing by not knowing what kind of variables it checks for TRUE in that array because it can be "Array", "HELLO", "MESS", 50 and length is 4 which is correct, but in the case I aam checking a simple string for length. Any easygoing explanation?

The problem is that at some point your condition ( $str[$len] ) will try to access an offset beyond the end of the string. That's your stopping condition, but that stopping condition throws the notice, since accessing an undefined offset is considered an error (and rightly so). You'll need to check whether the offset exists using isset($str[$len]) , which does not throw a notice.

You don't have to write a function to get the length of a string, PHP has this built in for you in several internal functions:

  1. strlen - Length of a string
  2. mb_strlen - Length of a string which may have multi-byte characters within it
  3. count - Length of an array or count of items in an object

If all you need is to count how long a string is, go with strlen , for arrays you'd use count . Much better than rolling your own.

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