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.
Related
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
}
}
I have a problem with comparing 2 values and let 1 value change within the if statement. But ofcourse when I reload the page it picks up the first value again. I'm using this code to set some information in a database when a machine is turned on or off.
$urlMachineON = 'http://192.168.0.150/awp/Shredder/PLCfiles/IOmachineActive.html';
// get content
$contentMachineON = file_get_contents($urlMachineON);
//remove first 2 characters
$truncate = substr($contentMachineON, 2);
//remove last 5 characters
$MachineOn = substr($truncate, 0, -5);
//MachineON can only be 1 or 0
$currentState = 2;
if ($MachineOn != $currentState)
{
$stmt = $conn->prepare("INSERT INTO machineactiviteit (Time, MachineStatus) VALUES(NOW(), ?)");
$stmt->bind_param('s', $MachineOn);
if ($stmt->execute() === TRUE)
{
$currentState = $MachineOn;
echo 'success';
}
else
{
echo $conn->error;
}
$stmt->close();
}
elseif($MachineOn == $currentState)
{
echo 'do nothing';
}
So when I do this he will always use the if statement since the $currentState and $MachineOn are always different from each other. In C# you have something like initalize component to set the value one time to a specific value. But I haven't found anything about that in php. So my question is can I set a value only once? Or should I solve this another way?
This is how it should work:
first attempt before: currentState = 2; MachineOn = 0; after: currentState= 0; MachineOn = 0;
second attempt before: currentState= 0; MachineOn = 0; after: currentState= 0; MachineOn = 0;
third attempt before: currentState= 0; MachineOn = 1; after: currentState= 1; MachineOn = 1; (I can change the MachineOn value with a button).
Just save $currentState value somewhere. For example in file or in database.
$currentState = file_get_contents('filepath'); // last saved state (check if is set!)
if($currentState !== $MachineOn) {
file_put_contents('filepath', $MachineOn); // Save current state
} else {
file_put_contents('filepath', 2); // Save other state
}
This is pseoudocode. Remember to check if file exist and has value.
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}
I'm calling in data from a JSON file. One of my elements is:
"mainImg_select":""
Sometimes this has a value, sometimes it won't - in this case it's empty. I put this (as well as other) variables in an object called Product.
When trying to set $product -> mainImg, I'm trying to see whether the JSON value is empty or not. If it's empty, I want to get the first value of another set of images, $more_imgsand make that the main image. Here's my code:
if(!is_null($mainImg)) {
$product->mainImage = $html->find($mainImg, 0)->src;
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
} else {
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (($idx == 0) && (!is_null($more))) {
$product->mainImage = $more->src;
} elseif (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
}
When I run the code, I get Notice: Trying to get property of non-object in relation to $product->mainImage = $html->find($mainImg, 0)->src;
I assume this has something to do with the if(!is_null($mainImg)) above it, because $mainImg SHOULD be null as defined in the JSON. If not, what's the best thing to use here?
EDIT: Here's some more detailed code for when the Product object is being set:
http://pastebin.com/EEUgpwgn
You should change !is_null to !empty as is_null() will return false even if "mainImg_select" is equal to empty string "".
Whether the $mainImg isn't found on your HTML; the code $html->find($mainImg, 0) will return null and then you will attempt to access the src parameter of a null object.
( from the Documentation of the php simple HTML Parser Library :
// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);
)
You have to do this:
if (null !== ($img = $html->find($mainImg, 0))) {
$imgSrc = $img->src; // Here the HTML Element exists and you can access to the src parameter
}
I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic