im not sure this is a good question to post but here is my issue. I have an if statement that is getting way too long and i was wondering if there is some other kind of syntax to shorten it out:
if (($time1 <= $one_day)&&
($time2 <= $one_day)&&
($time3 <= $one_day)&&
($time4 <= $one_day)&&
($time5 <= $one_day)&&
($time1 != NULL)&&
($time2 != NULL)&&
($time3 != NULL)&&
($time4 != NULL)&&
($time5 != NULL)){
//do sometihng
}
this is one example but i have a similar one that goes up to ..&&($time15 <= $one_day).
the statement is pretty self explanatory, $time1, $time2, etc can come back empty so i have to check if they are NULL or not
any ideas?
thanks
You can put the common stuff in a function:
function validate_time($time, $one_day) {
return $time <= $one_day && $time != NULL;
}
if (validate_time($time1, $one_day) &&
validate_time($time2, $one_day) &&
validate_time($time3, $one_day) &&
validate_time($time4, $one_day) &&
validate_time($time5, $one_day)) {
// do something
}
You may want to refactor code and eliminate the need for copying & pasting those checks. Another way to get the job done:
while (true) {
foreach (array($time1, $time2, $time3, $time4, $time5) as $time) {
if ($time > $one_day || $time == NULL) {
break 2;
}
}
// do something
break;
}
The above could be put in a function as well which would make the while-loop and break keyword redundant. Replace break 2 by return then.
Using an array for you variables would help. The you can iterate over them and check.
Put the times in an array and have a for loop to do the checking.
Instead of using 15 similar but different variables, consider using an array.
If you must (or want to) keep the original variable names and not use an array here is the good solution (for $time1 to $time5):
$ok = true;
for ($i = 1; $i <= 5; $i++)
{
$var =& ${'time'.$i};
if ( ! ($var <= $one_day && $var != NULL))
{
$ok = false;
}
}
if ($ok)
{
//do something
}
You can set all the values into an Array and compare it using an For Loop.
A functionised version which should help with your reuse. This is similar to Lekensteyns code.
$times = array(
'time',
'time',
'time',
'time',
'time',
);
function validateTime($checks, $limit)
{
foreach($checks as $check) {
if($check == null || $check > $limit) {
return false;
}
}
return true;
}
if(validateTime($times,$one_day) == true) {
//codey code.
}
Related
I'm having an issue with some code that someone else has previously worked on.
The goal is to iterate through a directory and push any files that are within a certain date range to an array (files are in mmddyyy.txt format).
The (terribly named, not by my own doing) variables in the code represent the following:
$aYear - A given year, read in from a text file. This variable changes during every iteration of the loop. The same goes for $aMonth and $aDay.
$sYear1 - Start year. $sMonth1 and $sDay1 are used in respect to $sYear1.
$sYear2 - End year. $sMonth2 and $sDay2 are used in respect to $sYear2.
$isGood - File will be added to the array.
$isGood = false;
if($aYear >= $sYear1 && $aYear <= $sYear2)
{
if($aYear == $sYear1)
{
if($aMonth == $sMonth1)
{
if($aDay >= $sDay1 && $aDay <= $sDay2)
{
$isGood = true;
}
}
else
{
if($aMonth >= $sMonth1 && $aMonth <= $sMonth2)
{
$isGood = true;
}
}
}
else if($aYear == $sYear2)
{
if($aMonth == $sMonth2)
{
if($aDay <= $sDay2)
{
$isGood = true;
}
}
else
{
if($aMonth <= $sMonth2)
{
$isGood = true;
}
}
}
else
{
$isGood = true;
}
}
if($isGood)
{
//echo "Found good article";
$a = $a . "===" . $file;
array_push($result, $a);
}
I'm not getting the results that I expected. I'm looking for some help as to how I can simplify this code and get it working properly. I do need to keep this solution in PHP.
Thank you in advance.
It seems to me Month statement if($aMonth >= $sMonth1 && $aMonth <= $sMonth2) needs work
eg start date- 03 Aug 2013 end date- 04 Sep 2016 and check date say 08 Nov 2013
would make isGood=false whereas it should be true.
Removing && $aDay <= $sDay2 and && $aMonth <= $sMonth2 should work.
As #Sandeep pointed out you're issues are with:
if ($aMonth >= $sMonth1 && $aMonth <= $sMonth2)
and
if ($aDay >= $sDay1 && $aDay <= $sDay2)
as you don't need to be comparing the date with end dates as well.
That being said you can clear up your code completely by doing something like:
$date = (new DateTime)->setDate($aYear, $aMonth, $aDay);
$start = (new DateTime)->setDate($sYear1, $sMonth1, $sDay1);
$end = (new DateTime)->setDate($sYear2, $sMonth2, $sDay2);
if ($start <= $date && $date <= $end) {
//echo "Found good article";
$a = $a . "===" . $file;
array_push($result, $a);
}
Hope this helps!
I got a weird problem.
I want a simple system which shows an error if there are more than 1 request in one second.
What i did:
if(!isset($_SESSION['protect']['mass_request_time']) || $_SESSION['protect']['mass_request_time'] = null) {
$_SESSION['protect']['mass_request_time'] = microtime(true);
$_SESSION['protect']['mass_request_request'] = 1;
} else {
$_SESSION['protect']['mass_request_request'] += 1;
if($_SESSION['protect']['mass_request_request'] >= 2 && microtime(true) - $_SESSION['protect']['mass_request_time'] < 1) {
die('Too many requests!');
} elseif(microtime(true) - $_SESSION['protect']['mass_request_time'] > 1) {
# Reset the counter since more than a second is over
$_SESSION['protect']['mass_request_time'] = null;
}
I have no clue what i did wrong, i guess the solution is pretty easy (maybe just a calculation error.. it's already 3 AM here).
Your first if statement isn't valid.
$time = $_SESSION['protect']['mass_request_time'];
if (!isset($time) || $time = null)
Your code just just sets the time to null. Use == instead.
function rawtransform{
if ($raw>=500 && $raw<=550){
$score= 1;
}
if ($raw>=550 && $raw<=600){
$score= 2;
}
if ($raw>=600 && $raw<=650){
$score= 3;
}
if ($raw>=700 && $raw<=750){
$score= 4;
}
if ($raw>=750 && $raw<=800){
$score= 5;
}
if ($raw>=800 && $raw<=850){
$score= 6;
}
if ($raw>=850 && $raw<=900){
$score= 7;
}
if ($raw>=900 && $raw<=950){
$score= 8;
}
if ($raw>=950 && $raw<=1000){
$score= 9;
}
}
This seems very basic and not very well coded. (I am only learning php )
Can anyone offer a better way of doing this? maybe a single if statement. I think there is a way just cant get my head round it.
Thanks
How about just using math?
function rawtransform($raw) {
$score = (int)($raw/50)-9;
}
You may want to add a range check for the input, though.
You can create a list of conditions, and loop through the and apply the if.
$conditions = array(
array(500, 550, 1), // greater than value, lesser than value, assignment value
array(550, 600, 2),
array(650, 700, 3) // add the rest of the conditions
);
foreach($conditions as $condition) {
if($raw >= $condition[0] && $raw <= $condition[1]) {
$score = $condition[2];
}
}
if ($raw >= 500 && $raw<= 1000){
$score = ceil(($raw-500)/50);
}
You can use if...else constructs.
if ($raw>=500 && $raw<=550){
$score= 1;
}
elseif ($raw>=550 && $raw<=600){
$score= 2;
}
elseif ($raw>=600 && $raw<=650){
$score= 3;
}
That way, if the script encounters a size of, say, 575 it won't even bother to go through the following conditions.
In your given example, the script can be simplified by:
function rawtransform($raw) { $score = floor(($raw - 450)/50); return $score; }
Your logic seems to be that you are subtracting 450 from raw, then dividing it by 50 and rounding down to the nearest whole number. (There are problems in your implementation however, as if raw is a factor of 50, it will meet the requirements for two of the if statements and there is a condition missing for when it falls between 650 and 700.)
You could do this as follows:
floor(($raw-450)/50)
I am wondering if I can set a variable to infinity, and if not what the best way to achieve my problem is. Take my function below:
public function seekValue($value, $column = null, $limit = null) {
$this->connect('rb');
$results = array();
while (!feof($this->_pointer)) {
$data = explode($this->_config->delimiter(), fgets($this->_pointer, 1024));
if(!is_null($column)) {
if ($data[$this->_config->columns($column, "string")->index()] == $value)
array_push($results, $this->formatRow($data));
} else {
if (in_array($value, $data))
array_push($results, $this->formatRow($data));
}
}
$this->disconnect();
switch (count($results)) {
case 0;
return false;
case 1;
return $results[0];
default;
return $results;
}
}
I set $limit = null in the function parameter list, however I later want to use $limit in my while loop like so while (!feof($this->_pointer) && count($results) < $limit) incase the user decides to pass an integer to it.
If this was the case I could do this:
if (!is_int($limit)) {
$limit = infinity;
}
To say that if $limit is not set run infinite times.
I hope this makes sense.
Just to answer the original question:
Yes you can set a variable to infinity by assigning INF
$x = INF;
var_dump($x > 10000); // bool(true)
var_dump($x - 100); // float(INF)
Why don't you just adapt the condition:
while (!feof($this->_pointer) && ( ($limit === NULL) || (count($results) < $limit)) )
Why not...
while (!feof($this->_pointer) && (is_null($limit) || count($results) < $limit))
This way if it isn't null is only when it will evaluate && count($results) < $limit
I had an interview today and the person asked me this question:
How do you find easily an item in a circularly sorted array
Since I didn't know the answer, I tried to find a solution. Here's what I have:
Thanks
<?php
function searchincircularsorterlist($a, $len, $num) {
$start=0;
$end=$len-1;
$mid = 0;
while($start<$end) {
$mid=$start+$end/2;
if ($num == $a[$mid]) {
return $num;
}
if($num<$a[$mid]) {
if($num<$a[$start] && $a[$start]<=$a[$start+1])
$start=$mid++;
else
$end=$mid--;
}
else {
if($num>$a[$end] && $a[$end-1]<=$a[end])
$end=$mid--;
else
$start=$mid++;
}
}
if ($start == $end && $num == $a[$start]) {
return $num;
}
return -1;
}
$array = array(7,8,9,0,1,2,3,4,5,6);
var_dump(searchincircularsorterlist($array,sizeof($array),4));
I am trying to work with a circularly sorted array but for some reason it does not work. What's wrong with my code?
1) learn priority of operations. You should have: $mid=($start+$end)/2; which you ended up dividing $end by 2 and then $start - the result. This is why you got an infinite loop.
2) use: $start=$mid+1; and not $start=$mid++; that will help reducing the number of loops
<?php
function searchincircularsorterlist($a, $len, $num) {
$start=0;
$end=$len-1;
$mid = 0;
while($start<$end) {
$mid=($start+$end)/2;
if ($num == $a[$mid]) {
return $num;
}
if($num<$a[$mid]) {
if($num<$a[$start] && $a[$start]<=$a[$start+1])
$start=$mid+1;
else
$end=$mid-1;
}
else {
if($num>$a[$end] && $a[$end-1]<=$a[end])
$end=$mid-1;
else
$start=$mid+1;
}
}
if ($start == $end && $num == $a[$start]) {
return $num;
}
return -1;
}
$array = array(7,8,9,0,1,2,3,4,5,6);
var_dump(searchincircularsorterlist($array,sizeof($array),4));