How to change name of a variable using another variable - php

Firstly, I wrote this code, but it's too long...
if ($option1 == 'true')
{
echo "it works";
}
if ($option2 == 'true')
{
echo "it works";
}
if ($option3 == 'true')
{
echo "it works";
}
if ($option4 == 'true')
{
echo "it works";
}
if ($option5 == 'true')
{
echo "it works";
}
if ($option6 == 'true')
{
echo "it works";
}
if ($option7 == 'true')
{
echo "it works";
}
So, I want to improve code and have something like this, but it doesn't work. I can't understand how to change the name of a variable of if inside the for.
Thanks for help.
for ($i = 1; $i <= 7; $i++)
{
if ($option($i) == "true")
{
echo "it works";
}
}
}

PHP has a feature called variable variables that you can use to dynamically reference variables based on string names. I wouldn't recommend using them because it leads to difficult to understand code later on. https://www.php.net/manual/en/language.variables.variable.php

Use curly braces to name a variable after a constructed string:
if ( ${"option$i"} == true ) …
… but as stated in the comments, if what you want to do is INDEXING a collection of variables using a incremental number, you want to use regular arrays, especially if you plan to move to other languages (like C) that don't support this way of referencing.
PHP also supports associative arrays which enables you to use a string rather than a number as an index, which makes them key->value pair collections.

Related

Compare 2 strings even if capital letters are included

I have a question about an if statement.
if($_POST['billing_first_name'] == $tet['data']['0']['first_name']) {
}
else
{
run code
}
This code compares a string that it gets from a form with an already existing string.
It works. But when i dont add a capital letter, it runs the code after all.
So for example if i compare String with String it doesnt run the code (which is what i want) But when i compare string with String it runs the code (which i dont want) Only because theres no capital letter included at the beginning. Is there a way to fix this?
Based on the comment the code is running fine it is an understanding of which block your are in.
if(condition){//code} will only run code when the condition is true ie
if("String" == "String"){echo "foo";} // will echo foo
if("string" == "String"){echo "foo";} // will not echo foo
In order to run code when false you add an else
// Will echo foo
if("String" == "String"){
echo "foo";
} else {
echo "bar";
}
// Will echo bar
if("string" == "String"){
echo "foo";
} else {
echo "bar";
}
A trick to getting ifs to execute when something is false is to use the ! (meaning not)
// Will echo bar
if("String" != "String"){
echo "foo";
} else {
echo "bar";
}
// Will echo foo
if("string" != "String"){
echo "foo";
} else {
echo "bar";
}
I solved it thanks to cmorrissey.
using strlower on both variables allows me to compare 2 strings no matter if there are capital letters inside one of the strings.
if(strtolower($_POST['billing_first_name']) == strtolower($tet['data']['0']['first_name'])) {
//do nothing
}else {
//run code
}

Elseif not returning the proper value on PHP

When the user introduces a letter and clicks on submit the script shall return a name that starts with that letter, I wrote it using a Switch/Case structure, now I need to write it using if/elseif/else.
The problem is that no matter what letter I introduce on the Textbox I'll always get the return for A (Aberdefia - Anacleto)
$nombrador=$_POST['nombrador'];
$nombrador=strtoupper($nombrador);
if ($nombradorIf = 'A') {
echo "Aberdefia - Anacleto";
} elseif ($nombradorIf = 'B') {
echo "Brígida - Brígido";
} else {
echo "Is that even a letter?";
}
The code for the letters C to Z is just like the one for A and B.
You need == for comparison, = is for assignment, and === is for identical or same type.
Also, you used $nombrador when assigning and $nombradorIf when comparing, resulting in an undefined variable.
if ($nombrador == 'A') {
echo "Aberdefia - Anacleto";
} elseif ($nombrador == 'B') {
echo "Brígida - Brígido";
} else {
echo "Is that even a letter?";
}
Thus, $nombrador == 'A' means $nombrador is equal to A.
And, $nombrador = 'A' means to assign A to $nombrador.
More information at http://php.net/manual/en/language.operators.comparison.php.
Hope this helps, thanks!
== is the conditional operator = is assigning operator
if ($nombrador == 'A') {
echo "Aberdefia - Anacleto";
} elseif ($nombrador == 'B') {
echo "Brígida - Brígido";
} else {
echo "Is that even a letter?";
}
Try this code
$nombrador=$_POST['nombrador'];
$nombrador=strtoupper($nombrador);
if ($nombrador == 'A') {
echo "Aberdefia - Anacleto";
} else if($nombrador == 'B') {
echo "Brígida - Brígido";
} else {
echo "Is that even a letter?";
}
Your code error near . you condition check variable name is $nombradorIf and also not declare variable but You assign the value variable name is $nombrador and you not use conditional operator == . so result not proper . You use above the code working fine
For checking conditional statement you have to use == (double equal sign) like below:
$nombrador=$_POST['nombrador'];
$nombrador=strtoupper($nombrador);
if ($nombrador == 'A') {
// ^^ Use like this
echo "Aberdefia - Anacleto";
} elseif ($nombrador == 'B') {
// ^^ Use like this
echo "Brígida - Brígido";
} else {
echo "Is that even a letter?";
}

Do I need to specify not to use the second variable in my second else if statement? If so, how?

If I want to create an if statement with 2 variables:
if ($variable1 && $variable2) {
// Do something
}
And then add another if statement below with only the first variable, how would I do it? Do I only include the one variable like this:
else if ($variable1) {
// Do something
}
Or do I need to specify that the first variable is true, not the second? If so, is this correct?
if ($variable1 && !$variable2) {
// Do something
}
Go for:
if ($variable1 && $variable2) {
// Do something
}
else if ($variable1) {
// Do something
}
the reason is for example if you write like this :
the following is wrong approach
if ($variable1) {
// if u have two variables $variable1 and $variable2
// and you want to validate both but if the $variable1 contains
// nonzero value it will never go to the else part
}
else if ($variable1 && $variable2) {
// Do something
}
now basically
else if ($variable1) {
// Do something
}
and
else if ($variable1 && !$variable2) {
// Do something
}
are same.you can use any of them if you are not toooo much concerned about the performance.
else if ($variable1) {
// Do something
}
is enough. Since the first if-statement will fail, it will evaluate the else if as a new statement

Compare strings in PHP

I'm trying to compare a POST variable with a string. Can someone help me see what in my PHP code is not written correctly? I've tried both '==' and '==='. Thank you for your help.
$action = mysqli_real_escape_string($mysqli, $_POST['action']);
if(strcmp($action, "save") == 0){
//do stuff
}elseif(strcmp($action, "load") == 0){
//do other stuff
}else{
//do even more stuff
}
why not simply use
if ($_POST['action']=='save'){
}elseif($_POST['action']=='load'){
}
don't understand the mysql in this contenxt
Don't know why you want to do this, but try casting $aciton, like (string)$action.
== is used to see if the two sides of comparison are equal, while === is used to check to see if they're identical meaning they are equal AND of the same type.
As for your code, you should just be able to do
if($action == 'save'){
echo 'save';
}
elseif ($action == 'load'){
echo 'load';
}
else{
echo 'none';
}

Replacement for nested IF's?

Sometimes mostly for processing user input i find myself using a lot of IF statements nested in each other, sometimes it is much more than below, to the point it goes from if on left side of screen to the if number 10 on right side of screen.
This is very difficult to read and troubleshoot, is there other way to do nested if?
I know about switch() however in this case i have to do query in third if rather than first.
if (true) {
if (true) {
if (true) {
...
echo "You are logged in";
} else {
echo "login failed"
}
} else {
echo "incorrect email";
}
}
I assume that your true conditions are real conditions, and not just the true boolean constant.
if (condition1 && condition2 && condition3) {
echo "You are logged in";
} else {
echo "login failed";
}
If you need a condition handled separately:
if (emailAddressIsCorrect) {
if (condition2 && condition3) {
echo "You are logged in";
} else {
echo "login failed";
} else {
echo "incorrect email";
}
Or you can just return early, which is cleaner in my opinion. You can do this for each condition, if you like. You can have as many conditions as you want with this arrangement, without requiring condition nesting:
if (!emailAddressIsCorrect) {
echo "incorrect email";
return;
}
Often times I'll do the "fail out" strategy instead:
function login() {
if (!condition1) {
echo "incorrect email";
return false;
}
if(!condition2) {
echo "incorrect password";
return false;
}
if(condition3) {
echo "logged in successfully!";
return true;
}
return false;
}
This example is suspect, there are security concerns with letting an attacker know which part of the login failed, but as a code snippet, you can see the strategy.
Combine 2 if statements using "&&".
OR
Sometimes using object oriented programming you can avoid if statements:
if(is type a) {
dostuff1();
} else if(is type b) {
dostuff2();
}
With classes and inheritance:
class->dostuff();
You can also use "first class functions" to avoid if statements.
Say you have values $_POST['page'] == 'page1', $_POST['page'] == 'page2'
$functions = array("page1"=>$function1, "page2"=>$function2);
function dostuff1() {
return 'a';
}
function dostuff2() {
return 'b';
}
$function1 = "dostuff1";
$function2 = "dostuff2";
$functions[$_POST['page']]();
instead of
if($_POST['page'] == '1') dostuff1();
etc... although this method is somewhat scary... lol
compare this:
if ($true1) {
if ($true2) {
if ($true3) {
...
with this:
if ($true1 && $true2 && $true3) {
...
}
with the first appoach not only you're wasting useful space for a single IF,
you are also delaying the inevitable: the optimization at a later day.
Also, it has no matter (etc. performance) if you place your IFs as nested or
in a single line because PHP intepreter will stop checking beyond if it finds
a FALSE.

Categories