PHP - better way of checking through variables one by one - php

I have a php application where users upload specific images, and the number of images can be different per user. I have a variable set on startup as false for each image that i change to true once its done.
For example one user might have to upload 3 and have so far done 2 so:
$required = 3;
$houseImageStatus1 = true;
$houseImageStatus2 = true;
$houseImageStatus3 = false;
Another then may have to upload 5 and have done them all:
$required = 5;
$houseImageStatus1 = true;
$houseImageStatus2 = true;
$houseImageStatus3 = true;
$houseImageStatus4 = true;
$houseImageStatus5 = true;
I need to be able to check that all required images have been uploaded before continuing. At the moment i have a very long-winded and ugly way be doing:
if($required==3){
if($houseImageStatus1==true &&
$houseImageStatus2==true &&
$houseImageStatus3==true){
// allow continue
}
else {
// pause
}
}
if($required==5){
if($houseImageStatus1==true &&
$houseImageStatus2==true &&
$houseImageStatus3==true &&
$houseImageStatus4==true &&
$houseImageStatus5==true){
// allow continue
}
else {
// pause
}
}
Can i do the above but in a much shorter and cleaner way? Maybe in some sort of array and loop through them as a function?

Use arrays for this purposse:
$houseImageStatus[1] = true;
$houseImageStatus[2] = true;
$houseImageStatus[3] = false;
and then check if all are true:
if (count(array_unique($houseImageStatus)) === 1 && $houseImageStatus[0] === true) {
// here you go
} else {
// nope
}

You Could use either:
Array and check for falses in array and by checking the index of array, You could determine the size (here you named it as $required).
OR
Using a counter which increments with each uploading of images....
Use different counters with different users . You dont have to give seperate variables for each user.. You could use any existing user dependant variables like user_id or user_name..

Store the boolean values in an array, use array_filter to remove the false values and then check the array size against your variable $required:
$houseImageStatus = array();
$houseImageStatus[0] = true;
$houseImageStatus[1] = true;
$houseImageStatus[2] = false;
// and so on
if(sizeof(array_filter($houseImageStatus)) == $required){
// everything is okay
}
else{
// something is wrong
}

You can do array with all values set to false:
$houseimages = array();
$n = 5; // How many pictures
for($i = 0; $i < $n; $i++) $houseimages[$i] = false; // Set all to false
And now, when user uploads one picture, just set $houseimages[0] = true; and so on.
Later just look through array and check if all values are true or not.

$required = 3;
$filled =0;
$houseImageStatus1 = true; $filled=$filled+1;
if ($required==$filled){//continue} else {//pause}

Related

avoid repeating variable due to undefined variable error

I'm trying to make a profile completion progress, which shows the percentage of how much a user has completed his profile settings. If a user has filled in a field, he receives +15 or +5, however, if the field is not filled in he receives +0.
the code I did is really bad, with variable repetitions, I wanted to know if you knew a cleaner way to do this.
if (!empty($user->avatar)) {
$avatar = 15;
} else { $avatar = 0; }
if (!empty($user->copertina)) {
$copertina = 15;
} else { $copertina = 0; }
// dati personali
if (!empty($user->name)) {
$name= 5;
} else { $name = 0; }
if (!empty($user->last_name)) {
$last_name = 5;
} else { $last_name = 0; }
[...]
if (!empty($user->biografia)) {
$biografia = 5;
} else { $biografia = 0; }
$personal = $avatar+$copertina+$name+$last_name+$sesso+$nascita;
$gaming = $steam+$battlenet+$xbox+$playstation+$switch+$uplay+$origin+$ds;
$social = $twitter+$facebook+$biografia;
$punti = $personal+$gaming+$social;
how do I remove all the others {$ variable = 0}?
You can't really, since you want the value to be a number, and not "undefined". You could initialize your variables to 0 like in this answer stackoverflow.com/questions/9651793/….
If you want to get into type comparisons for null variables, check php.net/types.comparisons. I would just initialize the variables to 0 and remove all the else.
OR...
modify your $user object to have all these variables in an array ($key:$value). You can then initialize the array to 0 all over, and modify it. Adding a new profile value would be easy, and adding array values is quick.
This snippet :
if (!empty($user->avatar)) {
$avatar = 15;
}
else {
$avatar = 0;
}
is semantically equivalent to :
$avatar = (bool)$user->avatar * 15;
Explanation:
Non-empty field gets converted to true and empty string or null gets converted to false
Because we do multiplication php true/false values gets converted to 1/0
So after multiplication you get 15 * 1 or 15 * 0 - depending if your field was used or not.

How to set a variable value based on conditions set by other variables

So I am new to PHP, and am currently just doing a little project as practice, I've managed to get down a few lines of code without falling over... but am a bit stuck here.
Essentially, what my script currently does is check three different variables that I have set (each a true/false option) and distinguishes if there is only one true option selected (out of the 3 options, only one can be true, the other 2 must be false). If only 1 value is set to true, the rest of the code runs; if multiple values are set to true, or no values are set to true, it shows an error prompt for the user.
Once this check is done, I wanted to then set the value of $name for example, based on records linked to the relevant variable that is true... This is what I have come up with, but it doesn't seem to work...
if ($value1 == "true") {$name = $result1;}
else if ($value2 == "true") {$name = $result2;}
else if ($value3 == "true") {$name = $result3;}
else exit (0)
So i essentially want to set the $name variable by identifying which of the 3 value variables is true, and then setting $name with the relevant variable retrieved in the $result
Any help would be appreciated. And before anyone goes off on one... I know I may sound a bit mad... but we all have to start somewhere!!
Thanks
It would look much nicer with a switch:
switch(true){
case $value1:
$name = $result1;
break;
case $value2:
$name = $result2;
break;
case $value3:
$name = $result3;
break;
default:
exit();
}
In case you need to make sure only one of the statements is true, validate that prior using this:
//In case you need to make there is only a single true statement
$found = false;
for($i=1; $i<4; $i++) {
$value = "value".$i;
if($$value) {
if($found) {
exit("More than one 'true' statement");
}
$found = true;
}
}
Dracony's answer looks nice indeed, but will fail when multiple values are set to true. For more flexibility, you should consider mapping the values into arrays, and tracking the state (amount of values that are true) with a flag variable. Find a fully commented example that will satisfy all conditions below. Additionally, this code will work with arrays of any length (you can add conditions by simply putting more values in $values and $results).
// store the data in arrays for easier manipulation
$values = array($value1, $value2, $value3);
$results = array($result1, $result2, $result3);
// set a flag to check the state of the condition inside the loop
// it keeps track of the index for which the value is true
$flag = -1;
$name = NULL;
// use for and not foreach so we can easily track index
for ($i = 0; $i < count($values); $i++) {
// if no index has been found 'true' yet, assign the current result.
if ($values[$i] === true) {
if ($flag === -1) {
$flag = $i;
$name = $results[$i];
}
// if a 'true' value has been found for another index
// reset the name var & stop the loop
if ($flag > -1 && $flag !== $i) {
$name = NULL;
break;
}
}
}
if ($name) {
// run code when only 1 value is true
} else {
exit();
}

Is it possible to create a for loop inside an if condition?

I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.

Comparing mysql data with folder files

I want to check if there are any image record in my database that is not in my folder of images, but I cant seem to find a way to do this and I dont know why, I made this code:
$result = mysql_query("SELECT imagen FROM galerias", $dbh);
$flag = true;
mysql_data_seek($result, 0);
while($row2 = mysql_fetch_assoc($result)) {
$directorio = opendir("../galeria/programas");
while ($archivo = readdir($directorio)) {
if($archivo == $row2["imagen"]){
$flag = false;
}
}
if ($flag) {
echo "IM NOT IN THE FOLDER ".$row2["imagen"]."<br>";
}
}
?>
It's only load one record only..
I think the mistakes is on the $flag, you did not reset the $flag after each check. So if there is one file that equals to the one on the DB, which makes the $flag false, the rest will be considered equals since $flag will be always false after that.
And it is better using strcmp for comparing string rather use "==". It is more binary safe.

Do the same - just with less code

I've been trying to work my way to it simply must check it with all inputs in the present that I might have 100 lines so got it done less to just check it all together for an error or what?
What I think about that: instead of taking 14 lines of code that make it less but may be the same,
if($_POST["email"] == "")
{
$error = 1;
}
if($_POST["pass1"] == "")
{
$error = 1;
}
if($_POST["pass2"] == "")
{
$error = 1;
}
if($_POST["fornavn"] == "")
{
$error = 1;
}
if($_POST["efternavn"] == "")
{
$error = 1;
}
if($_FILES["file"] == "")
{
$error = 1;
}
Just create an array of field names and loop over them...
foreach(array('email','pass1','pass2',...) as $field) {
if(empty($_POST[$field])) {
$error = 1;
}
}
$_FILES you will have to handle separately. You can create another loop if you want. The structure of $_FILES is different though; I think you should be checking the "error" field. Check the docs.
Another way to approach this, considering the fact that you don't seem to be performing different tests for each field, or responding with specific error messages, is to use array_diff_key:
$names = array('email', 'pass1', 'pass2', 'fornavn', 'efternavn', 'file');
$names = array_keys($names); // convert $names to keys
$posts = array_filter($_POST); // filter out any falsy values
$fails = array_diff_key($names, $posts); // check for the differences
$error = $fail ? 1 : 0;
If you then wish to respond with specific messages depending on what is missing, you already have a list of the problem parameters in $fails. If you wish to extend the above to take into account specific value checks, you could write your own array filter callback function and pass it's name as the second parameter to array_filter... however this wont allow you to choose a different filter response based on array key, only on array value. All because rather annoyingly array_filter doesn't receive a key value when filtering an array.

Categories