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>
3
  • 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. Commented Sep 12, 2016 at 13:25
  • Possible duplicate of Remove empty array elements Commented Sep 12, 2016 at 13:33
  • Thanks Sherif, that pointed me in the right direction and I have it working now. Commented Sep 12, 2016 at 15:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

No, that will remove the 0 / Fail values from the OP's example as well.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.