A better way to unset empty variables? - php

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);

Related

Getting Single Value From Chunked Array

In an array that is chunked into blocks of 11 values, I need to know if a particular one has a TRUE value. If only one is TRUE, that's all I need and the foreach can stop after it sets a value. All I could think of to do was to make it set a SESSION value to TRUE if a match but that does not stop the loop from continuing and then I had the issue of the SESSION giving false results unless it was then unset which I did after the value was set. Seems rather an indirect way to do it so any suggestions?
$FormValues = array_chunk($Fields, $NoValues); // Group together the field values
// Check if form uses multiple selection fields and add appropriate form tags
foreach ($FormValues as $multi) :
if (isset($multi[9]) === TRUE) $_SESSION['useMulti'] = TRUE;
endforeach;
$enableMulti = (isset($_SESSION['useMulti'])) ? " enctype=\"multipart/form-data\"" : "";
unset($_SESSION['useMulti']);
Here is an example of an array and, in this case, none should return TRUE:
$Fields = array("First Name","Title",$Title,1,0,30,"","","","","",
"Quote","Quote",$Quote,4,0,30,"","",$quoteSQL,FALSE,$siteDB,
"Location","Location",$Location,1,0,30,"","","","","",
"Date","EventDate",$EventDate,41,0,15,"",TRUE,"","","",
"Time","Time",$Time,39,0,0,"","",$sqlTime,"","",
);
You can simply iterate over the original array in strides of 11, rather than using array_chunk.
To make the loop stop iterating once you've found what you want, use break.
You don't need a session variable for this, they're only for preserving values between different PHP scripts. You don't really even need another variable, you can just set the enableMulti variable in the loop.
$enableMulti = "";
for ($i = 9; i < count($Fields); $i += $NoValues) {
if ($Fields[$i] === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
If you really want to use foreach you do need to use array_chunk, and you can also use array_column.
$enableMulti = "";
$chunks = array_chunk($Fields, $NoValues);
foreach (array_column($chunks, 9) as $value) {
if ($value === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
You can also get rid of the loop entirely:
if array_search(TRUE, array_column($chunks, 9)) {
$enableMulti = " enctype=\"multipart/form-data\"";
} else {
$enableMulti = "";
}

Cleaning up a very long if statement

I have a very long list of strings called $stringfilter1 $stringfilter2 etc all the way up to $stringfilter50
I have another string $reporteremail and I want to make a conditional statement whereby if any of the $stringfilter strings is present in the $reporteremail, some code is executed. At the moment my code looks like this and it works:
if (stripos($reporteremail, $stringfilter1) !== false || stripos($reporteremail, $stringfilter2) !== false || stripos($reporteremail, $stringfilter3) !== false [...]) {
runcode();
}
This is very very long though. I have cut it short here.
I was wondering if there's a cleaner, more efficient way to do this?
EDIT:
I am writing a plugin for a bug tracker. The strings are entered on another page in text boxes. I access them on this page by running a function that looks like
$t_filter = plugin_config_get( 'filter1' );
$stringfilter1 = string_attribute( $t_filter1 );
I would agree looping through an array would be the best way to do this. How can I push each new string onto the end of an array without having to write that snippet above out 50 times?
How can I push each new string onto the end of an array without having to write that snippet above out 50 times?
Try this:
$needles = [];
for ($i = 0; $i < 50; $i++) {
$t_filter = plugin_config_get("filter$i");
$needles[] = string_attribute($t_filter);
}
I have a very long list of strings called $stringfilter1 $stringfilter2 etc all the way up to $stringfilter50
[...]
This is very very long though. I have cut it short here.
I was wondering if there's a cleaner, more efficient way to do this?
Try this, it should go after the code block above.
$flag = false;
foreach ($needles as $needle) {
if (stripos($reporteremail, $needle) !== false) {
$flag = true;
break;
}
}
if ($flag) {
runcode();
}
The code above works by iterating through the $needles array and sets a flag if stripos doesn't return false. After it's finished iterating, it checks if the flag is true, if so, this means that one of the needles was found in the array.
EDIT
Alternatively, you could do it all in one loop, which is both faster and more efficient.
$flag = false;
for ($i = 0; $i < 50; $i++) {
$t_filter = plugin_config_get("filter$i");
$needle = string_attribute($t_filter);
if (stripos($reporteremail, $needle) !== false) {
// One of the needles was found in $reporteremail.
runcode();
break;
}
}
You don't need a loop. First put all your filters in an array instead of having them in separate variables. I would try to do this by modifying the input source rather than doing it in your PHP script. (Based on your comments I'm not sure if that's possible or not, so maybe you do need a loop like the one in the other answer.) Then you can use str_ireplace to check for your filter strings in the $reporteremail. (This will not modify $reporteremail.)
str_ireplace($filters, '', $reporteremail, $count);
if ($count) {
// run code
}
The $count parameter will contain a count of how many replacements were performed. If it's nonzero, then at least one of the filters was found in $reporteremail.

how to check PHP array's value without index offset error in 1 IF

Is it possible to check the value of a certain key in a PHP array in 1 IF statement? Right now, in order to not throw an index offset error I have to check if the key is set, then check its value.
if (isset($array[$key]))
{
if ($array[$key] == $x)
{
// do stuff
}
}
(sorry, accidentally put ! in first IF originally)
The && operator is short-circuit, thus:
if (isset($array[$key]) && $array[$key] == $x)
// do stuff
}
Happy coding.
You may also use a reference: if $array[$key] does not exist, then it will be created and set to null; therefore, no error will occur. This is most useful when you expect the value to exist; ie, you do not want to act specially if the value does not.
if (&$array[$key] == $x) {
}
try this. ur current code wont do anything bc if it is not set, the second if statement will never be...
if (isset($array[$key]) && $array[$key] == $x)
{
//do stuff if that key == $x
}
Yes, with the boolean operator && ;)
if (isset($array[$key]) && ($array[$key] == $x)) {
// do stuff
}
Best approach is using array_key_exists() function.
An example- array_key_exists($key,$array);
Check the documentation link more details.
if you have an associative array compare the size of array to the key index instead of the $key
if(sizeof($array) >= $key){
if ($array[$key] == $x)
{
// do stuff
}
}

How to compare POST response to array values?

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."
}

Debug simple php while code

I am getting this error: "Fatal error: Can't use function return value in write context in D:\Programas\wamp\www\away\index.php on line 18". Line 18 being the if statement.
Can anyone help me out on this? Thanks.
$vars = array("first_date_month", "first_date_day", "last_date_month", "last_date_day", "resume_date_month", "resume_date_day", "pay_date_month", "pay_date_day", "pay_time_hour", "pay_time_minutes");
$err_flag = false;
$i = 0;
while ($i < count($vars) and $err_flag == false)
{
if ( (!isset($_GET($vars[$i])) or ($_GET[$vars[$i] == "0") )
$err_flag = true;
$i++;
}
Maybe I'm not seeing well, but:
if ( (!isset($_GET($vars[$i])) or ($_GET[$vars[$i] == "0") )
You got a really awful mixup of parenthesis and square brackets. There's no such thing as
$_GET()
Big typo you have to correct.
Your code is a mess.
$_GET is an associative array and not a function (you are using the function call syntax passing $vars[$i] as an argument). In the second $_GET there's one ] missing.
Line 18 should be:
if ( (!isset($_GET[$vars[$i]]) or ($_GET[$vars[$i]] == "0") )
My take at it:
$vars = array("first_date_month", "first_date_day", "last_date_month", "last_date_day", "resume_date_month", "resume_date_day", "pay_date_month", "pay_date_day", "pay_time_hour", "pay_time_minutes");
foreach ($vars as $var) {
if ($err_flag = empty($_GET[$var]))
break;
}
8)
I assume the marked answer has... well.. answered the problems in your code, so just throwing out some optimizations:
using foreach() instead of while/for
is simple in many cases where we are
just iterating over an array - we can get the value and also the key if needed.
using the empty() function (returns true for anything null, false, 0, "", "0")
exit the loop when you're done using break
$_GET is a variable, an array -- and not a function.
It means you have to use array-access, with [], to get the data it contains.
So :
$_GET[$vars[$i]]
instead of
$_GET($vars[$i])
for the first time you are using $_GET.
And, for the second time, you forgot to close one ] ; which means you need to use :
$_GET[$vars[$i]]
instead of
$_GET[$vars[$i]
In the end, you while-loop should look like this :
while ($i < count($vars) and $err_flag == false)
{
if ( !isset($_GET[$vars[$i]]) or $_GET[$vars[$i]] == "0" ) {
$err_flag = true;
}
$i++;
}
Note I also added {} arround the body of the if condition ; this way, if you ever have to add something, you won't risk forgetting those ;-)
Change your line 18 if... to:
if ( (!isset($vars[$i])) or ($vars[$i] == "0") )
$err_flag = true;
$i++;
This mainly because I -and this is purely personal, I suspect- don't like using the $_GET[...] throughout the script; assign:
$variable_from_GET[] = $_GET['variable_name'];
and then use the $variable_from_GET array variable in your conditions which you -I presume- you did since you had a $vars array.

Categories