php for loop working on each itiration - php

the following code should return only "5" once (for first ittiration)
instead returning "5" for each iteration. AS "5555555555555555555555555"
$col11=5;
for($x=1; $x<=5; $x++) {
for($y=1; $y<=5; $y++) {
if("$col{$x}{$y}") {
echo $col11;
}
}
}

Your if condition is simply checking whether the string provided is a truthy value. Yeah, you are interpolating the $x and $y values but it's still just a string. What you can do is put together the name of the variable as a string, then use $$ to access the variable name dynamically. You can also use isset() to determine if the variable has been set.
<?php
$col11=5;
for($x=1; $x<=5; $x++){
for($y=1; $y<=5; $y++){
// Store desired variable-name as string in a temp variable
$variable = "col{$x}{$y}";
// Check this temp variable's existance by using referece variable ($$)
if (isset($$variable)) {
echo $$variable;
}
}
}
?>
Check Output here

Change your if condition like this:
$col11=5;
for($x=1; $x<=5; $x++){
for($y=1; $y<=5; $y++){
$val = "col{$x}{$y}";
if($$val)
{
echo $col11;
}
}
}

I don't understand when you want to echo $col11 ? Maybe you want to echo col for x=1 and y=1 so you can make this condition :
if ($x==1 && $y==1)
I'm not sure what you research ?

Related

How to apply if condition when it's parameter is coming into a variable?

I have assigned a condition into a variable. Then I tried to put that variable as a parameter of a if statement. But the code is not working. Please check my code:
$a = 8;
$final_str = '$a == 10';
if($final_str) {
echo 'Output 1';
} else {
echo 'Output 2';
}
The desired output should be Output 2. But it is not working. I always see Output 1. Please help me in this case.
Thanks in advance!
As per your request, the real problem here is this line of code:
$final_str = '$a == 10';
Although you have said that you cannot change the first two lines of code as it is what you have intended, I think that what you have intended and the result of this are two different things.
You see, you are defining '$a == 10' which is interpreted literally as a string value.
So you are trying to do something like:
if ('some string') ...
The result of this is true because a string that is not empty is a truthy value.
I think your intention however, was to test if the variable $a is equal to the integer value of 10?
In which case you actually need to do:
$final_str = $a == 10;
The result of this can be true or false depending on whether the variable $a is equal to 10 or not, that way your if condition will reflect the desired result?
EDIT:
If however you are trying to create some PHP code dynamically within your string you'd need to run it through eval and here is more information relating to the usage.
EDIT 2:
I would rather try to re-factor this into something more like:
$thisPage = 8;
$truthyPages = array(10,20);
if (in_array($thisPage,$truthyPages)) {
echo 'positive output';
} else {
echo 'negative output';
}
Or maybe even:
$a = 8;
// Step 1
$final_result = $final_result || $a == 10;
// Step 2
$final_result = $final_result || $a == 20;
if ($final_result) {
echo 'success';
} else {
echo 'failure';
}

PHP - check if range appears in variable?

I have a variable like this :
$test = "002,003,004,005,012,032,045";
I'd like to see if any number in a range of numbers appears in this string.
eg : if ($test == [010-015]) echo "found";
this would check the $test variable for any number of 010,011,012,013,014,015 and if any is found then echo found.
How do I do this ?
Only way I can think of is to loop through each number .. but there must be a better way !
Thanks
hope this helps you
$test = "002,003,004,005,012,032,045";
foreach (explode(',',$test) as $i)
{
if($i > 10 && $i < 15)
{
echo 'found';
}
}

Is there something wrong with my for loop/if statement?

I have a for loop within a for loop and right before I enter an if statement, two values echo out and are equal. When I evaluate (with the if statement) whether or no they are equal, the values do not evaluate to even. Could there be something that I am not seeing that is wrong with this statement?
for($x = 0; $x < count($movies_total);$x++){
for($j = 0; $j < count($ask_array);$j++){
echo $movies_total[$x]->question_id.' '.$ask_array[$j].'<br>';
if($movies_total[$x]->question_id == $ask_array[$j]){
echo 'no';
}
}
}
You should dump both your variables ( $movies_total[$x] , $ask_array ) for us to know the problem but my guess would be you have white spaces. You can compare variables after trim:
if( trim($movies_total[$x]->question_id) == trim($ask_array[$j]) )

Multiple Conditions in a while loop PHP

What is the correct way to use boolean operators to have multiple conditions in a while loop?
I have this script here that I feel SHOULD work, however it comes up blank when I run it.
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
for ($i=0; $i<strlen($string); $i++) {
if ($string[$i] == chr(34)) {
// chr 34 is ascii value for double quote chr 44 is for comma
while (($string[$i] != chr(34)) && ($string[$i+1] != chr(44))) {
echo $string[$i];
$i++;
}
}
}
Ideally what i want is for the script to echo the the given string up until the pointer ($i) reaches a double quote and one ahead of it is a comma. I feel like this is very simple and I am clearly missing something obvious.
if ($string[$i] == chr(34)) {
while (($string[$i] != chr(34)) && ($string[$i+1] != chr(44)))
Your if statement will run if this character is a quote. The while statement will run for as long as this character isn't a quote (and isn't a comma)
The two are exclusive. I think you might be able to get around it by incrementing $i after the if statement, but there's almost certainly an easier way of doing this.
The if and the while says the opposite condition... which means the while will never have a true. I guess you wanted to check the next character ?
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
for ($i=0; $i<strlen($string); $i++)
{
if ($string[$i] == chr(34))
{
while (($string[$i+1] != chr(34)) && ($string[$i+1] != chr(44))) // notice the $i+1
// chr 34 is ascii value for double quote chr 44 is for comma
{
echo $string[$i];
$i++;
}
}
}
The inner loop will not end at the end of the string.
Manipulation the loop control variable ($i) inside the loop leads to difficult code.
It makes it much harder to reason about it, and check if it is correct or not.
You should avoid it.
You get a better structure if you have only one loop that move through the string one char after another. Than use a variable to remember a state, for example $inside_quotes .
You have a logical flaw inside your loop which will cause it to iterate over the whole string but without doing any output.
Let's say:
$a = 1;
$b = 1;
while ($a == 1)
{
while ($a != 1 && $b == 1)
{
# will never come here.
}
$a++;
}
Because $a can never be 1 and !1 at the same time the condition you have put inside each other are blocking themselves.
One common way to solve this is to tokenize the string (scan the string) and then work on the tokens:
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
$token = strtok($string, '"');
while ($token !== false)
{
$token[0] !== ',' && (print "$token\n");
$token = strtok('"');
}
This produces (Demo) the following output:
JOHN
<31255555656>
DAHDI/1-1
Which might or might not be what you are looking for. A more detailed variant of this is to have a tokenizer/scanner that has state, one that can do more (but still has the shortcoming that the escapes of the quotation marks by doubling ("") them). As this is pretty bogus, I only link it. It is bogus because:
The actual function you're looking for is called str_getcsv:
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
echo implode("\n", str_getcsv($string));
Output (Demo):
"JOHN" <31255555656>
DAHDI/1-1
3948723
If you have a whole file, take a look at the SplFileObject.
Since you already located the first quote with the for statement you don't need to locate the same quote again with the for statement.
remove this: (($string[$i] != chr(34)) && along with the extra ) and the code will produce the following:
"""JOHN"" <31255555656>"DAHDI/1-1"
<?php
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
for ($i=0; $i<strlen($string); $i++) {
if ($string[$i] == chr(34)) {
while ($string[$i+1] != chr(44)) {
echo $string[$i];
$i++;
}
}
}
?>

In php how do you say if ($x == 1 or 2 or 3 or 4) {do function} without repeating code many times?

Im not great in php and I could do with a little help. I want to say something like
if ($x == 1 or 2 or 3 or 4) {do function}
but the only way i know how to do that is to go
if (($x == '1') or ($x == '2')) or...
which seems a long way of doing it. Is there a better way I am missing, like
if ($x == 1,2,3,4) {do}
Thanks for your answers!
you can use in_array function
$array = array(1,2,3,4)
if(in_array($x, $array)) {
// do something
}
switch ($x) {
case 1:
case 2:
case 3:
case 4:
// do
break;
}
Or you can use the in_array() function creating an array such as $a = array(1,2,3,4); and then do if (in_array($x, $a)).
If you are concerned about space, you can also use the shortcut:
if (in_array($x, array(1,2,3,4))) { /* do */ }
You can create an array of expected values and then use function in_array().
http://php.net/manual/en/function.in-array.php
If it's a range, you could do:
if ($x >= 1 && $x <= 4) { }
You could also construct an array and check if the number is in that array.
<?php
$data = array(1,2,3,4);
if(in_array($x, $data)){
// execute function
}
?>
All the above ideas are good. I am going to show another way, that is not better, but is different.
You can store comparations in variables, to use later or combine. This helps readability, and make complex expresions easy to create and read. It obviusly remove any repetition.
$is_number = ($str=="one" or $str=="two" or $str=="tree");
$is_english = ($str=="one" or $str=="horse");
$is_french = ($str=="baguette" or $str=="amie");
$is_fun = $is_french or $is_english;
if($is_french and !$is_number){ ... }

Categories