Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have
$room=$_POST['room'];
$lastMTime=$_POST['lastMTime'];
function _getLastMsg($rName, $lMT){
$r=$rName.'.xml';
$rXML=simplexml_load_file($r) or die('Not found');
$rLMT=$rXML->lastMT;
if($lMT<$rLMT){
//some code here
}
}
How do I echo every $rXML->username that has $rLMT > $lMT?
I want to get all usernames that have been submitted after $lMT.
may be you can try this code
<?php
$var = [11, 10, 20, 30, 40];
for($i=0; $i<count($var)-1; $i++) {
if($var[$i]>$var[($i+1)]) {
echo "var $var[$i] > var ".$var[($i+1)];
}
}
?>
First of all make sure that all these vars should not be an array instead. When you have multiple variables which are handled in the same way usually it is a clear sign that they should be an array instead.
If not - you can use compact function to make variable names into array with their names and values, read the manual on it. Other way to access variable value by its name is variable variables - $$
Using the variables into your example you can do this
$i = 0;
while ($i <= 3) {
$varName = 'var'.$i;
if ($$varName > $var) {
echo $$varName;
}
$i++;
}
But that is no right way to iterate over an array. There exists a million other ways to iterate over a bunch of variables and print them, all of them are not the "right" way to do it. In your example code there is no array, where there should be one. Like this
$var = 11;
$vars = [10, 20, 30, 40];
# iterate and echo each element of $vars array)
foreach ($vars as $current) {
if ($current > $var) {
echo $var;
}
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I find myself doing the following quite a bit:
if (isset($objs[$key]){
$objs[$key] += val;
} else {
$objs[$key] = $val;
}
Is there a better way to do that?
Another way could be:
$objs[$key] = isset($objs[$key]) ? $objs[$key] + $val : $val
Is there a better way?
The easiest way to simplify could be a function taking the array by reference and deduplicate the code.
If you are using php 7 you can also make use the new ?? operator (assuming all values are integers):
$arr[$key] = ($arr[$key] ?? 0) + $value;
However, if you know the shape of the array you should base your actions on that. Create the array using array_fill_keys or similiar in that case.
If you are always adding numbers... you could do something like this to keep a single line of code for each entry which may or may not be preferable for you to your existing solution.
$objs = array();
addvalue($objs, "dog", 2);
addvalue($objs, "dog", 5);
// $objs['dog'] will = 7
function addvalue(& $var, $key, $value){
if (isset($var[$key])){
$var[$key] += $value;
} else {
$var[$key] = $value;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is it possible to do something like this:
if ($boolean == true) {
foreach ($variables as $variable) {
}
// some code that can be run either with a loop or without
if ($boolean == true) {
} // end the foreach loop
}
Or is there another way to do this without rewriting the same code twice just to satisfy all possibilities?
The conventional way is to always use a loop. If there is only one item, then you can still loop just once.
Contrived example
$values = …;
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $value) {
// Do your work
}
I'm not sure if I understand exactly what you're asking, but if you want to run a loop at least once, and continue looping for a condition then "Do While" is your answer. A do while works just like a while, but checks AFTER the first loop is run - meaning it always runs at least once.
PHP Docs for Do While
Do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.
Example:
$arrayofstuff = array('one ','two ','three '); // Optional array of stuff
$i=0; // Counts the loops
echo 'starting...';
do {
// Do stuff at least once here
// Array stuff if needed
if(isset($arrayofstuff[$i])) {
echo $arrayofstuff[$i]; // Uses loop # to get from array
} else {
break; // ends loop because array is empty
}
$i++;
} while (true);
For what it's worth, forcing a variable into a single value array would probably be easier to read. As you can see there's a lot going on here for such a simple task.
(Dionne Warwick voice) That's what functions are for:
function doSomething() {
//whatever
};
if ($boolean)
for($variables as $variable) doSomething();
else
doSomething();
That kind of syntax you thought about isn't valid in PHP. It's a very clever idea though. But code maintenance of one of there would bring hell on earth. Better forget it.
why not just plain:
if($boolean){
foreach($a as $b){
// do stuff
}
}else{
// do other stuff
}
What you want would be done like so...
foreach ($variables as $variable) {
// some code that can be run either with a loop or without
if ($boolean !== true) {
break;
}
}
But this is not as readable as just using an if/else statement
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want my page to display an error message "lorem ipsum" if the input for $a (from the $_POST super global) is greater than a defined maximum value ($max1 and $max2). So this is what I did:
$max1 = 2.7432;
$max2 = 274.32;
$a = $_REQUEST['a'];
function maximum(){
if ($a>$max1 || $a>$max2){
echo "<script language=javascript> alert(\"Lorem Ipsum\");</script>";
return maximum();
}
}
then I call the function here like so:
if(($fred=="fred") && ($george=="george") {
//check validity of input first by calling maximum;
maximum();
}
This is not working! What am I doing wrong?
This is a scope issue. $a, $max1, and $max2 is not in scope inside of your function. You need to pass it as a parameter for it to be available (i.e. in scope) within your function.
Also, your function doesn't work. In a nutshell you need to return the string from your function and then capture or echo it out when calling the function.
$max1 = 2.7432;
$max2 = 274.32;
$a = $_REQUEST['a'];
function maximum($a, $max1, $max2){
if ($a>$max1 || $a>$max2){
return "<script language=javascript> alert(\"Lorem Ipsum\");</script>";
}
}
if(($fred=="fred") && ($george=="george")) {
//check validity of input first by calling maximum;
echo maximum($a, $max1, $max2);
}
Please change your function like bellow and check the comments what mistake you did
function maximum()
{
global $max1,$max2,$a;//make $a,$max1,$max2 available inside this function
if ($a > $max1 || $a > $max2) {
echo "<script language=javascript> alert(\"Lorem Ipsum\");</script>";
//return maximum(); remove this line. Otherwise itwill go infinte loop
}
}
http://php.net/manual/en/language.variables.scope.php
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am not sure if this is even possible or if it makes sense but I want to set a variable to contain this loop:
<?php
do{
$x = $x + 1;
} while ($x<=5);
?>
Can this be accomplished with a variable variable?
I suspect you're looking to create a function:
function fun($x) {
do {
$x = $x + 1;
} while ($x <= 5);
return $x;
}
Then in your code you can simply write:
$x = fun($x);
Do you mean like this?
<?php
$varVar = rand(0,10);
for ($i=1; $i<=$varVar; $i++)
{/*the loop*/}
?>
I'm not really sure what you mean, unless you're after something similar to the block syntax of Objective-C?
I'm presuming you're new to PHP, and if so, are you sure you're not looking for functions? What you've done above will make the value of $x equal 5, if you wanted to do this with a function it would look like:
<?php
function doSomething($count) {
do {
// do something here
} while ($x <= $count);
}
doSomething(5);
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I am doing wrong with the following code? I want to compare if the element $my_id is present within the array $arr. If it is present return TRUE else return FALSE.
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
else
{
return FALSE;
}
}
You could replace that with...
return in_array($my_id, $arr);
...assuming you don't really want to return FALSE if the first element does not match.
If that is actually what you wanted, you could use...
return $arr[0] == $my_id;
If you want to leave your code mostly intact, just move the return FALSE to outside of the loop body.
The issue you are having is that you aren't looping entirely through the array. You are returning true/false after the first item in the array, irrespective of subsequent array entries after [0]
Well, I believe you should remove the else statement, unless you always just have one element in the array. I mean -- from the example you're showing, you're exiting the loop with this. I doubt this is what you want.
If you just need to know, if a value is within a given array
in_array($value, $array);
Maybe you want get the index of (the first occurence of) the value too
$index = array_search($value, $array);
if ($index === false) {
// Not in array
} else {
echo $array[$index];
}
The error in Your code is to return false on $arr[$i] != $my_id. The algorithm should look something like this:
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
}
return FALSE;
P.S. This isn't the best solution for this problem in PHP language. You should use one from alex.