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';
}
}
Related
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';
}
I am a beginner in PHP and I am trying to separate the input based on the argument. Following is my code but it seems that my $arg variables is never set. Can someone point out my error?
$sender = $_GET['sender'];
$receiver = $_GET['receiver'];
$message = $_GET['message'];
$temp = explode( '.', $message);
$tempcnt = count($temp);
echo $temp[$tempcnt - 1];
if($tempcnt > 2)
{
if($temp[$tempcnt-1] === 'mp4')
{$arg = 3;}
elseif($temp[$tempcnt-1]==='jpg')
{$arg = 2;}
else
{$arg = 1;}
}
echo "Value of arg is" . $arg;
I have even tried with == and === and strcmp in if but still same issue.
Try This:
<?php
$temp strrchr("foo.jpg",".");
if($temp==".mp4")
$arg = 3;
elseif($temp==".jpg")
$arg = 2;
else $arg = 1;
?>
See also the other answers, but one possibility that hasn't been mentioned is that == and === and strcmp all compare case sensitively. So they won't find extensions like .MP4.
The solution in that case would be to use strcasecmp.
However, the first thing to do with problems like this is to output some more diagnostics, so that you can see for yourself what goes wrong. In this example, echo $tempcnt; after its assignment, or else echo "did nothing" after the outer if {..} block.
That way you'll be able to follow what the program flow is.
Issue was caused since i didn't realize i had compared for args > 2. Made it >=2 and viola it done!!
Thanks to #barmar for pointing that out!
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]) )
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++;
}
}
}
?>
I am doing this check on a variable:
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
And what I was hoping for is that if num is null or not a number or doesn't exist, to make $population = -1 and in all other cases to give $population the value of $num
But that is not happening for me. Any ideas why this isn't working the way I thought it would?
Is this possibly an issue with scoping?
<?php
$num=23;
tryStuff();
function tryStuff(){
global $num; //if this line is commented out, then -1 is printed.
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
echo "$population<br>";
}
?>
is_numeric should work good by itself. If instead of $num the value was a super global, using isset would be a good idea to avoid warnings:
$population = is_numeric ($num) ? $num : -1;
// or
$population = isset($_GET['num']) && is_numeric($_GET['num']) ? $num : -1;
post an example of $num
using regex:
$population = preg_match("/^\d+$/", $num) ? $num : -1;
I'm going to go out on a limb here and say that you're inputting the number 0 and getting unexpected results, because empty(0) is true.
I think if you change your code to:
if (!isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
You will get the desired results.
EDIT Possibly you are looking for an Integer or a Float in which case you should replace is_numeric with is_int or is_float respectively.
Why not flip it around and go with a positive as a primary check?
$population = (isset($num) && is_numeric($num)) ? $num : -1;
I've never had fun with negative's and "or" statements :)
What happens if you var_dump($num);?
Personally, my guess is that PHP is interpreting something input as a number, when you are expecting it to be a string. Such examples might include things which might accidentally convert, like '0xFF' (a string of the Hex for 255).
Clearly the issue is not about isset, because if it were, you would have caught it, and you said to evolve that this happens even without empty. This means that something which you are expecting to be is_numeric($num) === FALSE can be evaluated as TRUE.