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条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路