You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改给定PHP循环代码,统计成功与错误的总次数?

Solution to Track Success and Error Counts in Your PHP Script

Got it, let's tweak your code to properly track and output the total success and error counts you need. First, let's fix a couple of small issues in your original code, then add the counting functionality step by step:

  1. Fix the loop increment bug: Your current code has $i++ both in the for loop declaration and at the end of the loop body. This makes each iteration increment $i twice, so your loop will only run 51 times instead of 101. We'll remove the extra $i++ inside the loop.
  2. Fix the preg_match pattern: PHP's preg_match requires delimiters (like /) around the regex pattern to work correctly—your original pattern is missing these.
  3. Add count trackers: We'll initialize two variables to keep tabs on how many times we get a success vs. error.
  4. Output final stats: After the loop finishes, we'll print the totals in the exact format you requested.

Here's the revised code:

<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

// Initialize counters to track success and error counts
$successCount = 0;
$errorCount = 0;

for ($i = 0; $i <= 100; $i++) {
    $url = "site.com";
    $h = [
        "Accept-Language: en-US,en;q=0.8",
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $h);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $x = curl_exec($ch);
    curl_close($ch);
    
    // Check if the response contains the HTML doctype
    if (preg_match('/<!DOCTYPE html>/', $x)) {
        echo "Success\n";
        $successCount++; // Increment success counter
    } else {
        echo "Error\n";
        $errorCount++; // Increment error counter
    }
}

// Print the final statistics in your desired format
echo "Success {$successCount} times and error {$errorCount} times";
?>

Quick Notes on Key Changes:

  • Counter Variables: $successCount and $errorCount start at 0, and we increment them each time we hit a success or error case.
  • Fixed Loop: Removing the extra $i++ ensures the loop runs exactly 101 times (from 0 to 100 inclusive, which matches your original intent).
  • Robust Regex: If the target site's doctype has extra whitespace or uses uppercase letters, you can adjust the regex to /<!DOCTYPE\s+html>/i—the i flag makes it case-insensitive, and \s+ accounts for any spaces between DOCTYPE and html.

If you don't need to see each individual success/error message during the loop, just delete the echo "Success\n"; and echo "Error\n"; lines inside the loop to clean up the output.

内容的提问来源于stack exchange,提问作者Eyus Wap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:27:47