How to compare POST response to array values? - php

I'm having difficulty comparing the $_POST from a user input to a set of array values.
I've set the following variable ...
$response = $_POST['answer'];
... and selected a range of possible correct answers and stored them in an array ...
$solutions = array('answer1','answer2','answer3');
I've tried checking/comparing like this ...
if (value($response) !== ($solutions)
{$error['result'] = "Wrong answer.";}
I know it's the line if (value($response) !== ($solutions).

in_array() is your friend:
$correct = in_array($response, $solutions);

If you want to compare array values;
as harakiri wrote in_array() is your friend.
However if you want to compare array keys, you have to use;
array_key_exists()
I would like to warn you tho, if your array contains a lot of information checking it with in_array() will slow you down.
Instead you will have to go with isset() to check if it is set, it is much faster than in_array().

$answer = false;
foreach ($solutions as $sol)
{
if ($sol == $_POST['answer'])
{
$answer = $sol;
break;
}
}
if ($answer)
{
//GOOD
}
else
{
$error['result'] = "Wrong answer."
}

Related

PHP: how to condition max(array_filter) & min(array_filter) if empty

I have created an array using compact:
$rank_month = compact('jan','feb','mar');
Like this and the data will be fetch using queries and due to that the data will sometimes will be empty and the data will be numbers.
And then I'm using the max(array_filter) and min(array_filter) to get the highest and lowest in the array but when the query is empty I get the
ERROR: max(): Array must contain at least one element
ERROR: Min(): Array must contain at least one element
is it possible to condition it like:
if(empty(max(array_filter('$rank_month')))){
$high = ""; }
else{
$high = max(array_filter('$rank_month'
}
or is their any way to fix this error? Even if the data is empty
Thanks.
You are passing array_filter a string when it actually wants an array. '$rank_month' is an 11-character string, it's not an array.
You want to make sure you pass the array to array_filter (as well as min and max).
You also want to be checking the length of the filtered array before calling min/max.
$filtered_month = array_filter($rank_month);
if(!empty($filtered_month)){
$high = max($filtered_month);
}
else{
$high = '';
}
simply what the error says: $rank_month is an empty array
use sizeof or count
if (sizeof($rank_month) > 1) {
$high = max($rank_month);
} else {
...
}
Or
if (count($rank_month) > 1) {
$high = max($rank_month);
else {
...
}
You need to check if the Array is empty, not if the max value is empty.
You also don't need to pass in array_filter, the array itself should work.
if(empty($rank_month)){
$high = "";
} else {
$high = max($rank_month);
}

Checking if all values in one array exist in another array

I am trying to check if all required values exist in an array. I thought using array_intersect would be what I should be using:
$required[0] = 'FirstName';
$required[1] = 'LastName';
$posted['Email'] = 'none#example.com';
$posted['FirstName'] = 'Bob';
$posted['Group'] = '5';
print_r(array_intersect($required, $posted));
So, I want to be sure that "FirstName" and "LastName" exist in the $posted array. However, "LastName" is missing, but this returns an empty array result.
What am I missing?
If $posted originally comes from $_POST at some point, (as in the values from inputs on a form), all of the keys will be set, even though some may be set to ''. Since you have keys as values in your $required array, It's probably best to just check the required fields in a loop. You can use empty to simultaneously verify that they exist and have truthy values. Assuming the following code is the body of a function or the contents of a file, something like this should work:
foreach ($required as $requirement) {
// if everything has to have a value, just return false as soon as something doesn't
if (empty($posted[$requirement]) return false;
}
return true;
Part of why the way you're doing it with array_intersect isn't working because that function will check the values in $required against the values in $posted, and you need to check the values in $required against the keys in $posted. The other part is that array_intersect will return the values that the two arrays have in common, not the ones that are missing.
If some of the keys in $posted really may not exist, it may be better to define your $required array by key instead of by value, and then use array_diff_key.
$required['FirstName'] = true;
$required['LastName'] = true;
$missing_requirements = array_diff_key($required, $posted);
If every key in $required is present in $posted, the result will be an empty array, which will evaluate to false.
print_r(array_intersect($required, array_keys($posted)));
Simple solution:
if (count(array_intersect($required, array_keys($posted))) == count($required) ) {
return true;
} else {
return false;
}

A better way to unset empty variables?

Currently I am checking if the $_FILES array is empty to unset like so:
if ($var === 'AP' && empty($_FILES['field_1']['name'])) {
unset($_FILES['field_1']);
}
if ($var === 'AP' && empty($_FILES['field_2']['name'])) {
unset($_FILES['field_2']);
}
if ($var === 'AP' && empty($_FILES['field_1']['name']) && empty($_FILES['field_2']['name'])) {
unset($_FILES['field_1']);
unset($_FILES['field_2']);
}
This is for image uploads, it works when there are a small amount of images that can be uploaded. Now I'm going to have 15 upload fields with them all being optional. Is there a better way to unset those arrays that are empty without doing conditionals like above for each and every possible combination?
Instead of unsetting the ones that are empty, why not set the ones that are set?
(This is good practice, since you may want to perform some validation action on the ones that are set)
$clean = array();
foreach($_FILE as $fileKey => $fileValue){
if($fileValue) {
$clean[$fileKey] = $fileValue;
}
// if you really want to unset it :
else{
unset($_FILE[$fileKey]);
}
}
for ($x = 0; $x < 15; $x++) {
if ($var === 'AP' && empty($_FILES[$x]['name'])) {
unset($_FILES[$x]);
}
}
Should do the trick. (Could use a check to make sure elements are set and some cleanup, but you get the idea)
It will actually be $_FILES['name'][0] not $_FILES[0]['name'] ,etc so just remove the empties:
$_FILES['name'] = array_filter($_FILES['name']);
Then just use $_FILES['name'] as the array to loop over and the keys will still be the same as the other arrays.
You can use array_filter to remove empty elements:
$emptyRemoved = array_filter($linksArray);
If you have (int) 0 in your array, you may use the following:
$emptyRemoved = remove_empty($linksArray);
function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
EDIT: Maybe your elements are not empty per say but contain one or more spaces... You can use the following before using array_filter
$trimmedArray = array_map('trim', $linksArray);

PHP: A better way of getting the first value in an array if it's present

Here's my code:
$quizId = '';
foreach ($module['QuizListing'] as $quizListing) {
if ($quizListing['id']) {
$quizId = $quizListing['id'];
break;
}
}
Is there a better way of doing this?
What you're doing is reasonable assuming that:
multiple quiz listings appear; and
not all of them have an ID.
I assume from your question that one of both of these is not true. If you want the first quiz listing then do this:
$listing = reset($module['quizListing']);
$quizId = $listing['id'];
The reset() function returns the first element in the array (or false if there isn't one).
This assumes every quiz listing has an ID. If that's not the case then you can't get much better than what you're doing.
Slight change:
$quizId = '';
foreach ($module['QuizListing'] as $quizListing) {
if (isset($quizListing['id'])) {
$quizId = $quizListing['id'];
break;
}
}
to answer if this array is coming from a database you probably have to better to filter your query not to include those row at first place
something like
SELECT * from Quiz WHERE id <> 0
this would give you an array usable without any other processing.
$quiz = array_shift($module['QuizListing']);
if (null != $quiz) {
echo "let's go";
}
Using array_key_exists you can check if the key exists for your array. If it exists, then assign it to whatever you want.
if (array_key_exists('id', $quizListing)) {
$quizId = $quizListing['id'];
}

PHP - Is there a way to verify all values in an array

Using PHP..
Here is what I have.. I'm gonna explain the whole thing and maybe someone can help me with the logic and maybe point me in the right direction.
I have a mail system I am working on. In the cc part, I am allowing the user to seperate the values by a semicolon, like so: 1;2;3;4...
When these values are passed to my function, I am using explode to get them into an array. What I want to do is some checking first. I want to firstly make certain that the format is correct and that every value is correctly seperated. If not, I should show an error. Once this is done, I want to make certain that every number is actually valid. I can query the database, put the reslts into an array and was thinking to use the in_array() function to verify this but I'm not certain that it will work. Can someone please help me out with the best way to handle this?
Thanks.
EDIT:
What is the best way to detect a bogus value in the CSV list of values?
In order to verify that each number was correct seperated, you want to check that there is no whitespace in the answer. So something like this should work:
$text = trim($id);
if(strpos(" ", $id) !== false)
{
//error
}
Next, to check for the values, it is very simple
if(!in_array($id, $database_ids))
{
// error
}
Finally, if you are only using numeric values, check that the id is numeric
if(!is_numeric($id))
{
//error
}
To combine, wrap it into an array
foreach($exploded_array as $key => $id)
{
$id = trim(id);
if(!is_numeric($id))
{
//error
}
if(strpos(" ", $id) !== false)
{
//error
}
if(!in_array($id, $database_ids))
{
// error
}
}
I hope the code was pretty self explanatory where it got the variables, but if you need me to explain more, feel free to ask.
You are looking for something like:
foreach ($array as $value) {
//do checking here
}
array_filter could be an option.
As whichdan suggested, here is an implementation that relies on array_filter():
<?php
function checkValue($value)
{
$id = trim(id);
if(!is_numeric($id))
{
return false;
}
if(strpos(" ", $id) !== false)
{
return false;
}
if(!in_array($id, $database_ids))
{
return false;
}
return true;
}
$values = '1;2;3;4';
$values_extracted = explode(';', $values);
if(count($values) == count(array_filter($values_extracted), 'checkValue'))
{
// Input was successfully validated
}
?>

Categories