0

I have a form which ultimately I would like to calculate a percentage score from the values submitted. The issue I have is that some answers may be marked as n/a, so I need to be able to calculate only the total number of fields with data ( 0 for a fail, 1 for a pass). I have used an empty string for n/a answers as in the code below. I'm new to php, so was wondering what the best way to go about this is. Is there a way to count the number of empty strings submitted, or perhaps count only the total number of strings submitted which contain data?

<label>
    <input type="radio" name="item1" value="">N/A
</label>
<label>
    <input type="radio" name="item1" value="0">Fail
</label>
<label>
    <input type="radio" name="item1" value="1">Pass
</label>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Iterate through all of the inputs. Either remove the ones with `""` value from the existing array or add the other ones to a new array. Then count and sum. – Patrick Q Sep 12 '16 at 13:25
  • Possible duplicate of [Remove empty array elements](http://stackoverflow.com/questions/3654295/remove-empty-array-elements) – Sherif Sep 12 '16 at 13:33
  • Thanks Sherif, that pointed me in the right direction and I have it working now. – misterpauly Sep 12 '16 at 15:19

2 Answers2

1

To answer your question in general, you can filter your array, removing the empty strings and then counting the number of items. If you compare that to the number of items in the original array, you know how many empty strings there were. And you can do that for any value you want to measure.

$filtered = array_filter($original, function($el) {
    // check for empty strings as 0 for example is a valid value
    return $el !== '';
});
var_dump(count($original) - count($filtered));

However, for forms you would have to see if you can use this as I would normally validate the individual fields.

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • Thanks jeroen, I've got it working now. I tried it with your code, but it kept returning a result of 0. I'm still a newbie to this so I've probably not followed it correctly. The code I got to work below is pretty similar. `$score = array($_POST['item1'], $_POST['item2'], $_POST['item 3']); $potential_score = sizeof(array_filter($score, function($value) { return $value !== ''; })); print_r($potential_score);` – misterpauly Sep 12 '16 at 15:18
0

sure - when the form is submitted you can process the $_POST array - in this example using array_filter with a custom callback.

function countempty($value){
    /*return empty( $value );*/
    return $value=='';
}

$empty=count( array_filter( $_POST, 'countempty' ) );
echo 'Empty: '.$empty;
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46