Do the same - just with less code - php

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.

Related

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

PHP solution - Check if string value is NOT in array (not working)

I am trying to validate 3 scenarios but something is wrong and the if statements are not being honored properly
Here are the scenarios I need to work:
If the string "2.5.4.15" exists in array then output "Extended Validation".
If the string "2.5.4.15" does NOT exist in array then output "Organization Validated".
If the string "id-at-organizationName" does NOT exist in array then output "Domain Validated".
I am getting incorrect results. For example, if the data I am parsing does contains "2.5.4.15" for some reason its returning "Domain Validated" ??
Here is my code:
if(isset($cert['tbsCertificate']['subject']['rdnSequence'])) {
$EV = array('2.5.4.15');
$org = array('id-at-organizationName');
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
for($i = 0; $i < $count; $i++) {
if(in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation = "<tr><td>Validation</td><td>Extended Validation (EV)</td></tr>";
echo $validation;
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation = "<tr><td>Validation</td><td>Organization Validated (OV)</td></tr>";
echo $validation;
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $org)) {
$validation = "<tr><td>Validation</td><td>Domain Validated (DV)</td></tr>";
echo $validation;
break;
}
}
}
-- UPDATE --
I removed the break; and I can see it's now returning multiple results before it gives our the correct one (highlighted in red the correct match).. but why is it returning the bogus response instead of just returning the correct response the first time ?
-- UPDATE 2 --
I think I understand the results I am getting, it seems to be outputting result for each iteration where the string is not found. Whereas what I want to do is return one response.
I think then because of this perhaps using a loop is not the answer. Is there a way to search the whole array for a string and output the result instead of looping through each array ?
I didn't understand why are you using 'array' to store single values, you can simple compare strings.
In case the field can match only to one option - you can use if..elseif or even better - switch.
Please notice that your $validation variable will always overwrite itself in every irritation. So, If you're looking for a specific row - you should mention it. If you're looking for one multi-result in the end, you need to store that data in another array.
In continuation to the chat, let me break the scenarios of the key's value:
If 2.5.4.15 exists in the array - return EV
If it (1) doesn't exist but 'id-at-organizationName' does - return
If it (1) doesn't exist and (2) also doesn't exist - return
For the first scenario I used break since if it exists we don't need to continue to check the rest of the array, also it's automatically means that the 2 other conditions could never exist. EDIT also added a break to the second scenario condition.
Here is my suggestion: (Please check it and share the output/problems in the chat until will accomplish to solve your problem)
if(isset($cert['tbsCertificate']['subject']['rdnSequence'])) {
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
for($i = 0; $i < $count; $i++) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'];
if($value == "2.5.4.15") {
$output = "EV";
break;
} else {
if($value == "id-at-organizationName") {
$output = "OV";
break; //Edit 1
} else {
$output = "DV";
}
}
}
echo $output;
}
You echoes bad variables:
for($i = 0; $i < $count; $i++) {
if(in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation = "<tr><td>Validation</td><td>Extended Validation (EV)</td></tr>";
echo $validation;
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $EV)) {
$validation1 = "<tr><td>Validation</td><td>Organization Validated (OV)</td></tr>";
echo $validation1; // $validation1 instead of $validation
break;
}
if(!in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $org)) {
$validation2 = "<tr><td>Validation</td><td>Domain Validated (DV)</td></tr>";
echo $validation2; // $validation2 instead of $validation
break;
}
}
The second thing is that for this task is better to use elseif instead of 3 ifs:
for () {
if () {
// validation
} elseif () {
// validation 1
} elseif () {
// validation 2
}
}

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.

PHP - better way of checking through variables one by one

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}

Undefined Index (Laravel)

I'm bashing my head against my desk trying to figure out why this PHP code is causing this error: Undefined index: arr. I'm using Laravel, and this code works like gold outside of it, but inside Laravel, it's returning the undefined index error.
Here's the code:
function set_pilots_array($line_array)
{
$airports = $this->airports;
$pilots = $this->pilots;
foreach($airports as $airport)
{
if($airport == $line_array[11] || $airport == $line_array[13])
{
if($airport == $line_array[11])
{
$deparr = "dep";
}
if($airport == $line_array[13])
{
$deparr = "arr";
}
$this->pilots[$deparr][] = array($line_array[0], $line_array[11], $line_array[13], $line_array[7], $line_array[5], $line_array[6], $line_array[8]);
}
}
}
function get_pilots_count()
{
$count = count($this->pilots['dep']) + count($this->pilots['arr']);
return $count;
}
This sort of goes with my other question: Grab and Explode Data It's pulling the data from the data file using this code:
elseif($data_record[3] == "PILOT")
{
$code_obj->set_pilots_array($data_record);
}
Which later does this:
$code_count = $code_obj->get_pilots_count();
You do not have $this->pilots['arr'] set. In other words, if you look at the output of var_dump($this->pilots);, you shall see there is no arr key-value pair. I suggest you this fix:
$count = count((isset($this->pilots['dep']) ? $this->pilots['dep'] : array())) + count((isset($this->pilots['arr']) ? $this->pilots['arr'] : array()));
Actually, this is not a fix - this is more like a hack. To make your code correct i suggest you to set the default values for those $pilots['arr'] and $pilots['dep'] values:
function set_pilots_array($line_array)
{
$airports = $this->airports;
$pilots = $this->pilots;
foreach (array('dep', 'arr') as $key)
{
if (!is_array($pilots[$key]) || empty($pilots[$key]))
{
$pilots[$key] = array();
}
}
// ...
}
Well there is too little code to really figure out what is going on, but based on what I see:
if($airport == $line_array[13])
this condition is never being met and so $deparr = "arr"; never happens and because of this
count($this->pilots['arr']);
is giving an undefined index error
You can easily suppress this by:
$count = count(#$this->pilots['dep']) + count(#$this->pilots['arr']);
your problem is that you are accessing all of your indexes directly without checking if they exist first.
assume that in laravel something is causing the array to not be populated.
in order to fix this, you should either iterate through the array with a foreach, or do a if(!empty($line_array[13])) {} before accessing it.

Categories