开发者

PHP BASICS - typecasting dilemma

In the following code, $counter variable is typecast to store integers as per this line $counter=(int)fread($fp, 20); then why strlen($counter) is used. I mean, strlen returns length of a string however $counter now is already an integer variable. Same goes for substr($counter, $i,1). The program gives the desired result, it's just that I do understand as explained above.



$counter_file = "./count.txt";
$img_dir="./img";
if(!($fp=fopen($counter_file, "r"))) die ("Could not find $counter_file");
$counter=(int)fread($fp, 20);
fclose($fp);

$counter++;

for ($i=0; $i<strlen($counter); $i++){

 $img_src = $img_dir."/".substr($counter, $i开发者_运维百科,1).".jpg";
 $img_tag_str .="<img src= \"$img_src\" border=\"0\">";

 }
echo "You are visitor no. $img_tag_str.";

$fp=fopen($counter_file, "w");
fwrite($fp, $counter);
fclose($fp);

Regrds, seni.


If you pass an integer to as strlen method, this integer is cast to a string.

So strlen(23) will give 2; strlen(1234) will give 4.

Why may you need this? To know the number of digits in a number, for example. Even if it's probably not an optimal way to do it.

That's what happens in your sample code. The $counter variable is loaded from a file. A cast to an integer ensures that this is a real number, and not some random stuff¹. Then, a loop is used to go through every digit, and to display an image with this digit. That explains why we need to strlen and substr the integer.


¹ Why random stuff is bad here? Imagine the data in the file is "Abc", when you expect a number. The loop will output something like:

<img src="img/A.jpg" alt="" />
<img src="img/b.jpg" alt="" />
<img src="img/c.jpg" alt="" />

Since you don't have A.jpg, b.jpg or c.jpg, nothing will display.


$counter is cast to an int so that $counter++ will do a simple integer increment. Functions like strlen($counter) implicitly cast the $counter value to a string before returning the length


Even though $counter is an integer, certain functions that require a string can treat it as one. If $counter = 125, then strlen($counter) sees strlen('125') and gives you the correct result of 3.

The function will cast the value passed to is as a string, but the original is not changed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜