I'm adding an array of items from a form and if all of them are empty, I want to perform some validation and add to an error string. So I have:
$array = array(
'RequestID' => $_POST["RequestID"],
'ClientName' => $_POST["ClientName"],
'Username' => $_POST["Username"],
'RequestAssignee' => $_POST["RequestAssignee"],
'Status' => $_POST["Status"],
'Priority' => $_POST["Priority"]
);
And then if all of the array elements are empty perform:
$error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
You can just use the built in array_filter
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
So can do this in one simple line.
if(!array_filter($array)) {
echo '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
}
Implode the array with an empty glue and check the size of the resulting string:
<?php if (strlen(implode($array)) == 0) echo 'all values of $array are empty'; ?>
Please note this is a safe way to consider values like 0 or "0" as not empty. The accepted answer using an empty array_filter callback will consider such values empty, as it uses the empty() function. Many form usages would have to consider 0 as valid answers so be careful when choosing which method works best for you.
An older question but thought I'd pop in my solution as it hasn't been listed above.
function isArrayEmpty(array $array): bool {
foreach($array as $key => $val) {
if ($val !== '' || $val !== null) // remove null check if you only want to check for empty strings
return false;
}
return true;
}
you don't really need it.
You're going to validate these fields separately and by finishing this process you can tell if array was empty (or contains invalid values, which is the same)
simplify use this way:
$array = []; //target array
$is_empty = true; //flag
foreach ($array as $key => $value) {
if ($value != '')
$is_empty = false;
}
if ($is_empty)
echo 'array is empty!';
else
echo 'array is not empty!';
I had the same question but wanted to check each element in the array separately to see which one was empty. This was harder than expected as you need to create the key values and the actual values in separate arrays to check and respond to the empty array element.
print_r($requestDecoded);
$arrayValues = array_values($requestDecoded); //Create array of values
$arrayKeys = array_keys($requestDecoded); //Create array of keys to count
$count = count($arrayKeys);
for($i = 0; $i < $count; $i++){
if ( empty ($arrayValues[$i] ) ) { //Check which value is empty
echo $arrayKeys[$i]. " can't be empty.\r\n";
}
}
Result:
Array
(
[PONumber] => F12345
[CompanyName] => Test
[CompanyNum] => 222222
[ProductName] => Test
[Quantity] =>
[Manufacturer] => Test
)
Quantity can't be empty.
this is pretty simple:
foreach($array as $k => $v)
{
if(empty($v))
{
unset($array[$k]);
}
}
$show_error = count($array) == 0;
you would also have to change your encapsulation for your array values to double quotes.
Related
I would like to check all keys of a global GET array and do something, if it contains keys, other than some whitelisted ones from an array.
Let's say the current url is:
.../index.php?randomekey1=valueX&randomkey2=valueY&acceptedkey1=valueZ&randomkey3=valueA&acceptedkey2=valueB
Just for better visualization:
These GET parameters are all available in the global GET variable which looks something like this:
$GET = array(
"randomekey1" => "valueX",
"randomkey2" => "valueY",
"acceptedkey1" => "valueZ",
"randomkey3" => "valueA",
"acceptedkey2" => "valueB"
);
The keys I accept and want to let pass, I put into an array too:
$whitelist = array(
"acceptedkey1",
"acceptedkey2",
"acceptedkey3",
);
Now I want to check whether $GET contains any key other than the whitelisted. So in the URL example from above it should return "true", because there are keys in the $GET array which aren't in the whitelist.
Not only the existence of such an unknown (none whitelisted) key should trigger a true, but please also its emptyness!
Another example would be the following url:
.../index.php?acceptedkey1=valueZ&acceptedkey3=valueB
This should return false, because no other key other than the ones in the whitelist were found.
Unfortunately I was not able to find any modification of the in_array function or array_search which would fit these requirements, because as far as I know these functions are only looking for something specific, whereas in my requirements I am also looking for something specific (the whitelist keys), but at the same tme I have to check if some unknown keys exist.
Thank you.
It seems you want to determine whether an array contains keys that don't exist in a whitelist.
One way to find the difference between arrays is to use array_diff():
array_diff ( array $array1 , array $array2 [, array $... ] ) : array
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it can be used to return all keys from the URL that are not present in the whitelist:
$extrasExist = !empty( array_diff( array_keys($GET), $whitelist ) );
var_dump($extrasExist);
Here's a demonstration:
$get1 = array(
"randomekey1" => "valueX",
"randomkey2" => "valueY",
"acceptedkey1" => "valueZ",
"randomkey3" => "valueA",
"acceptedkey2" => "valueB"
);
$get2 = array(
"acceptedkey1" => "valueZ",
"acceptedkey2" => "valueB"
);
$whitelist = array(
"acceptedkey1",
"acceptedkey2",
"acceptedkey3"
);
$extrasExist = !empty(array_diff(array_keys($get1),$whitelist));
var_dump($extrasExist);
$extrasExist = !empty(array_diff(array_keys($get2),$whitelist));
var_dump($extrasExist);
bool(true)
bool(false)
Everything in PHP doesn't have to be all "lets find function that does exactly what I'm looking for". Just do a simple foreach loop, which can accomplish what you're looking for:
function clear_filter() {
$whitelist = array( "project", "table_name", "filterDates", );
foreach ($_GET as $gkey => $gval) {
if (!in_array($gkey, $whitelist)) {
return false;
}
}
return true;
}
You can also write it more simply, with one foreach loop like below:
function isValid() {
// Copy the array
$temp = $_GET;
// Loop through the array, and remove any whitelisted elements
foreach ($whitelist as $wkey) {
unset($temp[$wkey]);
}
// If count($temp) > 0, there are non whitelisted entries in the array.
return count($temp) === 0;
}
You can use the following function.
$check = checkWhitliest( $_GET, $whitelist ) );
var_dump ($check );
You can call the above function as
function checkWhitliest( $array, $whitelist ) {
$allKeys = array_keys ( $array); //Get all Keys from the array.
$diff = array_diff( $allKeys, $whitelist); //Get the values which are not in whitelist.
if( count ( $diff ) > 0 ) { //If the count is greater than 0, then there are certain extra kesy in $_GET
return true;
}
return false;
}
There are only two techniques that I would recommend for this task and both make key comparisons for performance reasons. Using array_diff() or in_array() will always be slower than array_diff_key() and isset(), respectively, because of how PHP treats arrays as hash maps.
If you don't mind iterating the entire $GET array (because its data is relatively small), then you can concisely flip the whitelist array and check for any key differences.
var_export(
(bool)array_diff_key($GET, array_flip($whitelist))
);
If performance is more important than code brevity, then you should craft a technique that uses a conditional break or return as soon as a non-whitelisted key is encountered -- this avoids doing pointless iterations after the outcome is decided.
$hasNotWhitelisted = false;
$lookup = array_flip($whitelist);
foreach ($GET as $key => $value) {
if (isset($lookup[$key])) {
$hasNotWhitelisted = true;
break;
}
}
var_export($hasNotWhitelisted);
Or
function hasNotWhitelisted($array, $whitelist): bool {
$lookup = array_flip($whitelist);
foreach ($array as $key => $value) {
if (isset($lookup[$key])) {
return true;
}
}
return false;
}
var_export(hasNotWhitelisted($GET, $whitelist));
All of the above techniques deliver a true result for the sample data. Demo of all three snippets.
I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!
I need to check if any item in an array, that is part of a $_POST array, has a value. The values in the empty array are set, so the above example will not produce the desired results. (This array is a subset of the full $_POST array).
(
[columns] =>
[coached_textbox] => 1
[item] => Array
(
[first] => Array
(
[coach_menu_value] => one
[coach_menu_name] => Menu One
)
[second] => Array
(
[coach_menu_value] =>
[coach_menu_name] =>
)
(
Is there a simple way to test if either array item has a value? I could test each item in the array for value, but that seems inelegant.
This example provided in earlier post gives a fine example on how to test a code initialized array() for values.
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
However, it doesn't work on an array set within a $_POST array.
Use a recursive function like below to traverse the array. The function will return true if the array contains at least one non-null value or non-empty string.
function traverseArray($arr){
$flag = false;
foreach($arr as $value){
if(is_array($value)){
$flag = traverseArray($value);
if($flag) return true;
}else{
if(isset($value) && $value != '') return true;
}
}
return $flag;
}
And this is how you should call this function,
(Suppose $array is your original array)
$isNonEmptyArray = traverseArray($array);
if($isNonEmptyArray){
// At least one element in the array is either
// non-null value or non-empty string
}else{
// Array is completely empty
}
Here's a live demo: https://eval.in/847211
You can filter out the empty values and check for empty():
if (empty(array_filter($_POST['item']['second']))) {
// It is empty
} else {
// It is NOT empty
}
Or even just check for falsey value:
if (!array_filter($_POST['item']['second'])) {
// It is empty
} else {
// It is NOT empty
}
I'm trying to modify an array when looping through it and increment certain values.
$data = ['traits' => [[['amt' => 1]]]];
var_dump($data['traits']);
foreach ($data['traits'] as $key => &$index) {
foreach ($index as $key => &$value) {
$value['amt'] = $value['amt']++; // This should increment
if (in_array($key, $input)) {
$i++;
$insert["field_".$i] = $key."_1";
}
}
}
var_dump($data['traits']); // SAME AS PREVIOUS VAR_DUMP
What you are doing in the loop is undefined:
$value['amt'] = $value['amt']++;
The outcome of that depends on what's evaluated first. In this case $value['amt']++ seems to be evaluated first and then assigned to $value['amt'] again; the side effect of the increment is lost.
On the other hand, the following statement will work as expected:
$value['amt']++;
$list = array(
[0]=> array(
[name]=>'James'
[group]=>''
)
[1]=> array(
[name]=>'Bobby'
[group]=>''
)
)
I am looking to update the item 'group' where the name is 'Bobby'. I am looking for a solution with the two following formats. Thank you in advance for your replies. Cheers. Marc.
array_push($list, ???)
and
$list[] ??? = someting
As far as I know, there's no way updating your array with one of the given syntax.
The only similar thing I can come on is looping over the array using array_walk ... http://www.php.net/manual/en/function.array-walk.php
Example:
array_walk($list, function($val, $key) use(&$list){
if ($val['name'] == 'Bobby') {
// If you'd use $val['group'] here you'd just editing a copy :)
$list[$key]['group'] = "someting";
}
});
EDIT: Example is using anonymous functions which is only possible since PHP 5.3. Documentation offers also ways working with older PHP-versions.
This code may help you:
$listSize = count($list);
for( $i = 0; $i < $listSize; ++$i ) {
if( $list[$i]['name'] == 'Bobby' ) {
$list[$i]['group'] = 'Hai';
}
}
array_push() doesn't really relate to updating a value, it only adds another value to an array.
You cannot have a solution that will fit both formats. The implicit array push $var[] is a syntactic construct, and you cannot invent new ones - certainly not in PHP, and not most (all?) other languages either.
Aside from that, what you are doing is not pushing an item on to the array. For one thing, pushing items implies an indexed array (yours is associative), and for another pushing implies adding a key to the array (the key you want to update already exists).
You can write a function to do it, something like this:
function array_update(&$array, $newData, $where = array(), $strict = FALSE) {
// Check input vars are arrays
if (!is_array($array) || !is_array($newData) || !is_array($where)) return FALSE;
$updated = 0;
foreach ($array as &$item) { // Loop main array
foreach ($where as $key => $val) { // Loop condition array and compare with current item
if (!isset($item[$key]) || (!$strict && $item[$key] != $val) || ($strict && $item[$key] !== $val)) {
continue 2; // if item is not a match, skip to the next one
}
}
// If we get this far, item should be updated
$item = array_merge($item, $newData);
$updated++;
}
return $updated;
}
// Usage
$newData = array(
'group' => '???'
);
$where = array(
'name' => 'Bobby'
);
array_update($list, $newData, $where);
// Input $array and $newData array are required, $where array can be omitted to
// update all items in $array. Supply TRUE to the forth argument to force strict
// typed comparisons when looking for item(s) to update. Multiple keys can be
// supplied in $where to match more than one condition.
// Returns the number of items in the input array that were modified, or FALSE on error.