How to check if a PHP POST array has any value set? - php

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
}

Related

PHP multidimensional arrays - return value from second key if value from first key exists

So not a stranger to PHP or arrays even, but never had to deal with multidimensional arrays and its doing my head in.
I have the output of a PHP to a server API and need to pull all the mac address values from the (dst_mac) keys, but only on the occasion the category (catname) keys value for each element is emerging-p2p
The format of the array is like this (intermediate keys and values removed for brevity)
[1] => stdClass Object
(
[_id] => 5c8ed5b2b2302604a9b9c78a
[dst_mac] => 78:8a:20:47:60:1d
[srcipGeo] =>
[dstipGeo] => stdClass Object
(
)
[usgipGeo] => stdClass Object
(
)
[catname] => emerging-p2p
)
Any help much appreciated, i know when im out of my depth!
From your example that is an array with a std class. you can use the empty funtion.
//checks if the first key
if (!empty($array[1]->_id)) {
echo $array[1]->dst_mac;
// or do what you want.
}
This example only applies to one array. use a loop to have this dynamically done.
EDIT: My answer was based on your question. Didn't realize you have to check the catname to be 'emerging-p2p' before you get the mac address?
// loop through the array
foreach ($array as $item) {
// checks for the catname
if ($item->catname === 'emerging-p2p') {
// do what you want if the cat name is correct
echo $item->dst_mac;
}
}
Is this what you want?
for($i =0;$i<count($arr);$i++){
if(isset($arr[$i]['catname']) && $arr[$i]['catname']=='emerging-p2p'){
echo $arr[$i]['dst_mac'];
}
}
If there is only one object that has 'emerging-p2p' cat name:
foreach ($your_list_of_objects as $obj) {
if ($obj->catname == 'emerging-p2p') {
return $obj->dst_mac;
}
}
If there are many:
$result = [];
foreach ($your_list_of_objects as $obj) {
if ($obj->catname == 'emerging-p2p') {
$result[]= $obj->dst_mac;
}
}
return $result;
Use for loop.
for($i =0; $i<=count($arr); $i++){
if(arr[$i]['catname']=='emerging-p2p'){
echo arr[$i]['dst_mac'];
}
}
To fetch all the mac where catname is emerging-p2p
//Assuming $arr has array of objects
$result_array = array_filter($arr, function($obj){
if ($obj->catname == 'emerging-p2p') {
return true;
}
return false;
});
foreach ($result_array as $value) {
echo $value->dst_mac;
}
You can use array_column if you need only mac address on the basis of catname.
$arr = json_decode(json_encode($arr),true); // to cast it as array
$temp = array_column($arr, 'dst_mac', 'catname');
echo $temp['emerging-p2p'];
Working demo.

PHP How to check if array has not key and value

I am using one custom CMS developed by someone and getting issue to check the array result.
The function returns an array of username by passing userids array.
Example Code
$all_users = "1,5,9,10,25,40"; // getting from database
$user_ids = explode(',', $all_users);
$usernames = get_userids_to_usernames($user_ids); //this returns usernames array by passing uesrids array
If the database has not users in the column than the function is returning weird empty / null array as below.
var_dump($usernames);
array(1) { [""]=> NULL }
print_r($usernames);
(
[] =>
)
Now issue is, I want to check if array is empty or has value in return but I have tried everything is_null, empty, count($usernames) > 0 but none of these working.
Can anyone please help me to check conditionally if array has value or empty like above empty result.
Here is a workaround
if (array_key_exists('', $a) && $a[''] === null) {
unset($a['']);
}
then check on emptiness
You can use in_array to check if the array has an empty value and array_key_exists to check the key.
in_array("", $array)
array_key_exists("", $array)
http://php.net/manual/en/function.in-array.php
http://php.net/manual/fr/function.array-key-exists.php
Iterate through array, and check if keys or values are empty or null
$newarray = [];
foreach($array as $key=>$value)
{
if(is_null($value) || trim($value) == '' || is_null($value) || trim($key) == ''){
continue; //skip the item
}
$newarray[$key] = $value;
}
If you want to use empty with it, try array filter
if (empty(array_filter($arr))) {
//Do something
}
Array filter will automatically remove falsey values for you, and you can include a callback should you need more flexability.

PHP Unset Command in If Statement Not Working

I would like to unset an HTTP Posted key from the array after it echoes the "1" result, but the unset doesn't seem to work. How can I fix this?
$keylist = array('HHH', 'GGG');
if (in_array($_POST["keys"], $keylist)){
echo "1";
unset($keylist[$_POST["keys"]]);
} else {
echo "0" ;
}
Appreciate any help,
Hobbyist
Your unsetting $keylist not $_POST
unset($_POST["keys"]);
You're using the wrong array key for unsetting (You're trying to unset $keylist["HHH"], not, say, $keylist[0]) - you'll need to retrieve the key from the array, and then unset that specifically in order to remove it from the keylist.
$index = array_search($_POST["keys"], $keylist);
if($index!==false) { //YES, NOT DOUBLE EQUALS
unset($keylist[$index));
}
If $_POST["keys"] is an array of keys, you'll need to use array_keys with a search_value instead.
Array_search documentation: http://php.net/manual/en/function.array-search.php
Array_keys documentation: http://php.net/manual/en/function.array-keys.php
EDIT: Adding a full, working example.
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
if(in_array($_POST["keys"], $keylist)) {
$indexToRemove = array_search($_POST["keys"], $keylist);
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Another example, this time checking the index itself to see if it is not false:
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
$indexToRemove = array_search($_POST["keys"], $keylist);
if($indexToRemove!==false) {
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Output:
1Array ( [0] => asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh [1] => derp2 ) Array ( [1] => derp2 )
I realize now that I only had one = on the $index!==false check - the reason you need two is because $index is 0 if you're removing the first element of an array. Per PHP documentation,
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE. Please read the section on Booleans for more
information. Use the === operator for testing the return value of this function.
in_array($_POST["keys"], $keylist) checks if the posted value $_POST["keys"] is present as a value in $keylist, but unset($keylist[$_POST["keys"]]) uses $_POST["keys"] as the key in $keylist to unset something.
Since in_array() returns true, the posted value is present in the array $keylist. But you can't do unset($keylist['GGG']) because that value is not set.
A simple solution is to use the same values as keys too:
$keylist = array('HHH', 'GGG');
$keylist = array_combine($keylist, $keylist);
More about array_combine().
Your array have keys. So "HHH" in keylist is $keylist[0] and not $keylist['HHH']. You can not unset it because you have to define the array key instead of the array value.
Try to search for the array value like this:
array_search($_POST["keys"], $keylist)
This will return the array key for you or false if its not found. Your full code should like look like:
echo "1";
$arrkey = array_search($_POST["keys"], $keylist);
if( $arrkey !== false ){
unset($keylist[$arrkey]);
}
Here the PHP Manual for the array_search function: http://php.net/manual/en/function.array-search.php

Condition failing even if the array values are empty

I have a piece of code where the condition fails even when the array is empty.
This is the code:
echo "<pre>";
print_r($_FILES['jform']['name']['gallery']);
which outputs
Array
(
[0] =>
)
This is the condition:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile))
{
//do something
}
It should fail, but the program enters the if block. Why?
As you can see from the print_r() the array is NOT empty - it has one element, which on the other side looks like white space or empty.
Update
I would recommend reading POST method uploads, where you'll learn that name is the original name of the file and tmp_name is a random name of the temporary file, that has been just uploaded.
According to my experience you should check the Error Messages.
The check you're interested is:
foreach ( array_keys( $_FILES['jform']['gallery'] ) AS $key ) {
if ( UPLOAD_ERR_OK == $_FILES['jform']['gallery']['error'][$key] ) {
// do the stuff with the uploaded file in $_FILES['jform']['gallery']['tmp_name'][$key]
}
}
Keep an eye on the names of the arrays where gallery is before name.
As you can see your array is not empty it has a blank element.
The work around is array_filter which will eliminate blank data
$array = array(0=>'');
$array1 = array_filter($array);
print_r($array1);
if(!empty($array1)){
echo "has elememt";
}else{
echo "empty";
}
This is what u need
UPDATE
What if the value contains multiple spaces, yes this could be handled using a call back function
$array1 = array_filter($array,"call_back_function");
function call_back_function($val){
return trim($val);
}
In your case print_r() told you that galfile == array('') // 1 element is in the array
According to the documentaion only array() // 0 elements is considered empty. So the if statement is executed correctly.
In your case you should write:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile) && !empty($galfile[0]) )
{
//do something
}
When you working with arrays, before checking for empty you can sanitize your array using array_filter or the similar functions:
$galfile = array_filter($_FILES['jform']['name']['gallery']);
if(!empty($galfile))
{
//do something
}
But when you use global array _FILES, more correctly is checks for error:
if($_FILES['jform']['error']['gallery'] == 0)
{
//do something
}
P.S. If you want to filtering all array elements, you can use filter_var_array

Checking if all the array items are empty PHP

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.

Categories