0

I'm working with a CSV file. when the user uploads the file. I parse the CSV then select the data from the array that I need. after that, I'm running a for loop to validate that data and saving the results in the array. but the problem is when I print the results array there's only result for 1 email and there are 4 emails. any suggestions?

$results = [];
$valid_emails = 0;
$invalid_emails = 0;

for ($i = 0; $i < $csv_array['row_count']; $i++) {
  $email = $csv_array['data'][$i][$email_column];

  $result = validate_email($email);
  $results['Email'] = $email;

  if ($result) {            
    $results['Result'] = 'valid';
    $valid_emails++;
  } else {
    $results['Result'] = 'invalid';
    $invalid_emails++;
  }

}

echo '<pre>';
print_r($results);
echo '</pre><br>';

echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';

3 Answers 3

1

Use $results[] to add one or more elements :

$results        = [];
$valid_emails   = 0;
$invalid_emails = 0;

for ($i = 0; $i < $csv_array['row_count']; $i++) {
    $email = $csv_array['data'][$i][$email_column];

    $result       = validate_email($email);
    $res['Email'] = $email;

    if ($result) {
        $res['Result'] = 'valid';
        $valid_emails++;
    } else {
        $res['Result'] = 'invalid';
        $invalid_emails++;
    }

    $results[] = $res;
}

echo '<pre>';
print_r($results);
echo '</pre><br>';

echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
Sign up to request clarification or add additional context in comments.

Comments

0

You are overriding results every time in your loop, try this

$results = [];
$valid_emails = 0;
$invalid_emails = 0;

for ($i = 0; $i < $csv_array['row_count']; $i++) {
  $email = $csv_array['data'][$i][$email_column];
$rowResult=[];
  $result = validate_email($email);
$rowResult['Email'] = $email;


  if ($result) {            
    $rowResult['Result'] = 'valid';
    $valid_emails++;
  } else {
    $rowResult['Result'] = 'invalid';
    $invalid_emails++;
  }
$results[]=$rowResult;

}

echo '<pre>';
print_r($results);
echo '</pre><br>';

echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';

Comments

0

$results contains only the last email validation. You should store multiple results, and not only the last ;-)

Something like :

  $results[$i]['Email'] = $email;

  if ($result) {            
    $results[$i]['Result'] = 'valid';
    $valid_emails++;
  } else {
    $results[$i]['Result'] = 'invalid';
    $invalid_emails++;
  }

  if ($result) {            
    $results[$i] = 'valid';
    $valid_emails++;
  } else {
    $results[$i] = 'invalid';
    $invalid_emails++;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.