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
Related
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.
This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}
In the example are two arrays, but actually may be other number of arrays (i do not know how many arrays i may have).
$some_name = array ( "Volvo_0",220,180, );
$array_name_for_variable[]='some_name';//here i create another array latter to loop through
$another_name = array ( "Volvo_1",221,181, );
$array_name_for_variable[]='another_name';
In the example i just want to print_r the arrays i may have. So i loop through $array_name_for_variable. Like
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
trying to print particular array (like print_r($some_name)), using this
echo '<pre>', print_r($['val_array_name_for_variable'], true), '</pre> $val_array_name_for_variable __<br/>';
but see error Parse error: syntax error, unexpected '[', expecting T_VARIABLE or '$'
}
This print_r($['val_array_name_for_variable']) is wrong. Tried this print_r( $[$val_array_name_for_variable] );. Also got error.
Any ideas what need to change.
Why all this and what i need...
I have 12 arrays, but i do not know which of 12 would be used in one particular page.
So page loads, some of the 12 arrays are defined (used).
I may write like if array_1 exists, then long html code using variables from the array_1.
Then again if array_2 exists and not empty, then repeat the same html code with variables from array_2.
But instead of copy-paste (repeating) html code i decided to loop through arrays existing in opened page and the long html code write only once.
You could solve the problem with:
$some_name = array ( "Volvo_0",220,180, );
$array_name_for_variable[]=$some_name;
$another_name = array ( "Volvo_1",221,181, );
$array_name_for_variable[]=$another_name;
then iterate through it:
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
echo '<pre>', print_r($val_array_name_for_variable, true), '</pre><br/>';
}
This will print all the elements in $array_name_for_variable.
Comment if you need any more changes to the output.
Explanation: What the code is actually doing is iterating through all elements of the array $array_name_for_variable. They it creates a key => value for each element in it. The value ($val_array_name_for_variable) on the first iteration would be: $some_name. The key ($i_array_name_for_variable) - the element position in the array, so on the first iteration it would be 0 (as it always start from 0).
If you don't need the element position you could do it like this:
foreach( $array_name_for_variable as $val_array_name_for_variable ) {
echo '<pre>', print_r($val_array_name_for_variable, true), '</pre><br/>';
}
It would generate exactly the same output as the previous code snippet.
For adding elements to the array you have to pass a variable and you were passing just a string.
EDIT:
Based on the newly added info the code should be:
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
if (array_key_exists($i_array_name_for_variable, $val_array_name_for_variable)) {
echo '<pre>', print_r($val_array_name_for_variable, true), '</pre><br/>';
} else {
//Code if the array does not exist.
}
}
References:
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.array-push.php
http://php.net/manual/en/function.array-key-exists.php
You may want to do something like this
$some_name = array ( "Volvo_0",220,180, );
$array_name_for_variable['some_name']= $some_name ;
$another_name = array ( "Volvo_1",221,181, );
$array_name_for_variable['another_name']= $another_name ;
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
print_r($val_array_name_for_variable);//prints the array
print_r($i_array_name_for_variable);// print the keys ex :- some_name
}
I have an array of html textbox element with name say date_field[]. There could be multiple fields in the form. After submission of the form to check whether at least one of the textbox is not empty, I used -
<?php
if(empty($_POST["date_field"])){
echo "Is empty";
}else{
echo "is not empty";
}
?>
It echoed is not empty no matter whether I fill or I didn't fill this date_field.
P.S. If I printed the form value using print_r
If I didn't put value
[followup_date] => Array
(
[0] =>
)
if I put value
[followup_date] => Array
(
[0] => 2012-12--14
)
Any help will be highly appreciated
Your "empty" array contains an empty string:
array(0 => '')
That's not an empty array. The only "empty" array is array().
You may want to run it through array_filter, which removes all elements evaluating to false (which also includes "0", be careful).
The array is not empty since it will contain one element per non-disabled form field (even when those fields are empty).
You could use the array_filter function as mentioned by #deceze, but remember that this would also remove some elements which a human wouldn't consider to be empty.
Therefore I'd rather run through the array myself and check if all elements are empty in the matter that you want. For example:
function all_is_empty(array $subject)
{
foreach($subject as $value)
if(str_len($value) > 0)
return false;
return true;
}
Usage:
if(all_is_empty($_POST["date_field"]))
{
echo "Is empty";
}
else
{
echo "is not empty";
}
If this was me, I'd probably also combine this with checking that all the fields were valid. So if you know all the fields in that array should be dates, check that they actually are :)
I know there are a lot of these, but I'm looking for something slightly different.
A straight diff won't work for me.
I have a list (array) of allowed tags i.e. ["engine","chassis","brakes","suspension"]
Which I want to check with the list the user has entered. Diff won't work, because the user may not enter all the options i.e. ["engine"] but I still want this to pass. What I want to happen is fail if they put something like "banana" in the list.
You can use array_intersect(), and check the size of the resulting array with the size of the input array. If the result is smaller, then the input contains one or more items not in the 'allowed' array. If its size is equal, all items in it are in the user's input, so you can use the array do do whatever you want.
Use array_diff();
$allowed=array("engine","chassis","brakes","suspension");
$user=array("engine","brakes","banana");
$unallowed=array_diff($user, $allowed);
print_r($unallowed);
This will return banana, as it is in $user, but not in $allowed.
array_diff(): http://nl.php.net/array_diff
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
if ( array_diff( $input, $allowed ) ) {
// error
}
$allowed_tags = array("engine","chassis","brakes","suspension");
$user_iput = array("engine", "suspension", "banana");
foreach($user_input as $ui) {
if(!in_array($ui, $allowed_tags)) {
//user entered an invalid tag
}
}