dozug64282 2014-04-10 00:49
浏览 96
已采纳

PHP计算for循环中if条件语句的值

I have a PHP code to see if one or many pictures exist. If the picture exist I could like to count them and echo the answer. This is my code:

<?php
//Start Pictures section - dictates that if there are pictures this section is shown - if not this section is now shown.
for ($x=1; $x<=21; $x++)  {
    if($x<=9) {
        $picValue = 'picture0'.$x;
    }
    else {
        $picValue = 'picture' . $x;
    }

    $imageURLpixel = ABSOLUTE_URL_IMG.$code.'/pixel/'. $picValue .'.jpg';

    //Check if the image exists or not
    $pictureCount = 1;
    if (@fopen($imageURLpixel,'r')) {
    $pictureCount++;    
    $pictureCounter = count($pictureCount);
    }

 echo $pictureCounter;

} 

?>

I have 3 pictures in my exampe and it is being output as 111111111111111111111 - I would the output to be as 3. I am not getting any errors in my error log.

  • 写回答

3条回答 默认 最新

  • dousi1875 2014-04-10 01:03
    关注

    Just to make it clear. The solutions are until this one are all fixing "some issues" with the code, but not all together.

    Here is my approach to make it clear, understandable and readable - maybe some learning curve etc.

    $baseUrl = ABSOLUTE_URL_IMG.$code.'/pixel/';
    $pictureCount = 0;
    
    // for the first 20 pictues
    for ($x=0; $x<21; $x++)  {
          // make it more readable and practical - see "sprintf"-documentation.
          $filename = sprintf('picture%02d.jpg', $x+1); // < is "one-based index"
    
          $fileUrl = $baseUrl . $filename;
    
          // if url exists, increase counter;
          if (@fopen($fileUrl,'r')) 
                $pictureCount++;
    
     }
     // total count of existing images.
     echo $pictureCount; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀