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;
}
Related
I need to ensure that all the elements in my array are empty strings to process an action. The way I am currently doing it is incrementing a variable each time an element is an empty string. Then I check the value of that variable against a certain requirement N. If N is met, the action is processed. Below is the snippet of the code that checks for empty strings. I am not sure if this is the best way to do it and think there has to be a better way to do it because basically I am hard coding that value N. Can anybody else suggest another approach?
function checkErrorArray($ers) {
$err_count = 0;
foreach ($ers as &$value) {
if ($value == '') {
$err_count++;
}
}
return $err_count;
}
Why don't you do:
function areAllEmpty($ers) {
foreach ($ers as &$value) {
//if a value is not empty, we return false and no need to continue iterating thru the array
if (!empty($value)) return false;
}
//if got so far, then all must be empty
return true;
}
It will not have to run through the whole array if a non-empty value is found.
You could also do a shorter version:
function areAllEmpty($ers) {
$errs_str = implode('', $ers);//join all items into 1 string
return empty($errs_str);
}
Hope this helps.
Just filter it and if it is empty then ! will return true if not empty it will return false:
return !array_filter($ers);
Or if you actually need the count of empty elements then:
return count(array_diff($ers, array_filter($ers)));
I wrote a small function to check the required fields of a form, are not empty.
The function accepts two arguments, 1st is an array with all values from $_POST superglobal.
2nd is the required fields array which I populate.
Have a look:
public $errors = array();
public function validate_fields($fields_array, $required_fields)
{
foreach ($required_fields as $key => $value)
{
if (array_key_exists($key, $fields_array))
{
# If key exists in $fields_array
# check that the key value inside $fields_array is set & isn't empty
# if it's empty, populate with an error
if(empty($fields_array[$key][$value]))
{
$this->errors[] = "{$key} is empty but in fields_array";
}
}
else
{
# Key does not exists in $fields_array
# Did someone temper with my html ?
$this->errors[] = "{$key} is not in fields_array";
}
}
return (empty($this->errors)) ? true : false;
}
The issue I'm having seems to be related to "if(empty($fields_array[$key][$value]))"
statement. my goal is to check that $fields_array key value is not empty based on $required_fields key. I'm sure the statement I'm using is off. If you see anything that you think can be written better, please let me know, as I am new to php. Appreciate the help.
I think what you're trying to do is:
if(empty($fields_array[$key])) {
//this means value does not exist or is FALSE
}
If you also want to check for empty-strings or white-space only, then you need something more than just empty. E.g.
if(empty($fields_array[$key]) || !trim($fields_array[$key])) {
//this means key exists but value is null or empty string or whitespace only
}
Do note that the above answers will only work for indexed arrays in >PHP 5.4. If you have an associative array you have to use isset instead of empty:
if(isset($fields_array[$key]) && trim($fields_array[$key]) != '')
See http://nl3.php.net/manual/en/function.empty.php, example #2
You don't need to select the value as an index just key. Where $fields_array[$key] = $value;
if(empty($fields_array[$key]) && trim($fields_array[$key]) != '')
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."
}
I have an array with numerous dimensions, and I want to test for the existence of a cell.
The below cascaded approach, will be for sure a safe way to do it:
if (array_key_exists($arr, 'dim1Key'))
if (array_key_exists($arr['dim1Key'], 'dim2Key'))
if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))
echo "cell exists";
But is there a simpler way?
I'll go into more details about this:
Can I perform this check in one single statement?
Do I have to use array_key_exist or can I use something like isset? When do I use each and why?
isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like
isset($arr[1][2][3])
is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).
However, if you have
$arr['a'] = null;
then
isset($arr['a']); // false
array_key_exists('a', $arr); // true
comment followup:
Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:
isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.
function recursiveIsset($variable, $checkArray, $i=0) {
$new_var = null;
if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable[$checkArray[$i]];
else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable->$checkArray[$i];
if(!isset($new_var))
return false;
else if(count($checkArray) > $i + 1)
return recursiveIsset($new_var, $checkArray, $i+1);
else
return $new_var;
}
Use: For instance
recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))
In my case in drupal this ment for me that the following variable existed
$variables['content']['body']['#object']->body['und']
due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed
$variables->content->body['#object']->body['und']
For a fast one liner you can use has method from this array library:
Arr::has('dim1Key.dim2Key.dim3Key')
Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.
Also, this method will work as expected for null value because it internally uses array_key_exists.
If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.
So yes, there is a simpler way using one single if statement like the following:
if (isset($arr['dim1Key']['dim2Key']) &&
array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
I prefer creating a helper function like the following:
function my_isset_multi( $arr,$keys ){
foreach( $keys as $key ){
if( !isset( $arr[$key] ) ){
return false;
}
$arr = $arr[$key];
}
return $arr;
}
Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.
Imagine you have this kind of array:
$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );
You can write something like this:
$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );
if( $arr ){
//You can use the variable $arr without problems
}
The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.
I have arrays, some are multidimensional as well. I need a way to know if all the values are NULL. What would be the most efficient and effective way of determining if ALL values of an array (as well as the values of the arrays within that array) are NULL?
So basically: search array, if all values are NULL, $flag = true
EDIT: The values are being pulled from a MySQL database where NULL is in the context of MySQL, if that makes a difference.
If i remember well db null fields become empty strings in php so you can use a function like this:
function isEmptyArray($array){
foreach($array as $val)
if((is_array($val) && !isEmptyArray($val))||(!is_array($val) && $val!="")) return false;
return true;
}
Depends on what would you use that flag for, but I think the best would be to query the database so it retrieves only non null values, like
select col1,col2,col3 from table where col1 is not null and col2 is not null
and col3 is not null
That said, a simple way to do something like that in PHP would be
//array_filter filters values that evaulate to fals
$result = array_filter($input);
if (count($result) == 0) { $flag = true; }
This will fail for multidimensional arrays and if zeroes or other values that get automatically converted to false are valid values in your array, if this is the case you have to build a recursive callback function and pass it as a second parameter to array_filter.
You may want to look at the array_filter() function, by default it strips out values that equate to false (this includes NULL).
I'm not sure if it'll work as is for mutli-dimensional arrays, but it has the option to use call back functions which would easily allow you to handle that.
Long story short, if you run array_filter on the array and you get an empty array returned then all your values are Null or equal to false - if you need to differentiate between these values in a strict sense, then you should use a call back.
Can be done recursively:
arrayIsFullyNull ($arr)
{
if (is_array($arr))
foreach ($arr as $val)
if (!arrayIsFullyNull($val))
return false;
else if (!is_null($arr))
return false;
else
return false; // it's not null, and not array => value
return true;
}
You could use a RecursiveArrayIterator to walk over all the values (leaves of the tree of of nested arrays).
Untested code:
function isNullOrNestedArrayOfNulls($array)
{
if (is_null($array)
{
return true;
}
else if (!is_array($array))
{
return false;
}
$allNull = true;
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($array),
RecursiveIteratorIterator::LEAVES_ONLY);
while ($iter->valid())
{
if (!is_null($iter->current())
{
$allNull = false;
break;
}
}
return $allNull;
}
This would have the advantage of avoiding a recursive function (which have the reputation of being rather inefficient in PHP).