Simple php string issue, - php

I`m stucked on a php code and my question is:
I`m working with php if and elseif to show something like this below:
<?php
$test_a = 0 to 10; (My problem)
$test_b = 11 to 20; (My problem)
$test_c = 21 to 30; (My problem)
$test = 50; (random value)
$something = 12;
$something_b = 5;
$something_c = 15;
?>
<?php
if($test>=$test_a){
echo $something;
}elseif ($test=<$test_b) {
echo $something_b;
}elseif (test=<$test_c) {
echo $something_c;
}
?>
My question is how do I work with range using if/elseif.
Thanks!

That obviously is not valid syntax. This really is just a basic if/else statement:
if($test>=0 && $test <=10){
echo $something;
}elseif ($test>=11 && $test <=20) {
echo $something_b;
}elseif ($test>=21 && $test <=30) {
echo $something_c;
}
Just check of $test is greater than or equal to value 1 or less than or equal to value 2. If not, move on to your next if statement.

Set your variables to the top of each range:
$test_a = 10;
$test_b = 20;
$test_c = 30;
if ($test <= $test_a) {
echo $something;
} elseif ($test <= $test_b) {
echo $something_b;
} elseif ($test <= $test_c) {
echo $something_c;
}
If you have lots of cases, it may be better to create an array and use a loop:
$tests = array (array ('limit' => 10, 'message' => $something),
array ('limit' => 20, 'message' => $something_b),
array ('limit' => 30, 'message' => $something_c)
);
foreach ($tests as $curtest) {
if ($test <= $curtest['limit']) {
echo $curtest['message'];
break;
}
}

Related

Summerize all fields if exists from database

I have different fields in the database and im fetching their values.
Now what I would like to do is subract a number if certain field exists in database.
Here is my code:
<?php
$percent_profile_image = 40;
$percent_cover_image = 20;
$percent_profiletext = 10;
$percent_travelintext = 10;
$percent_sparetimetext = 10;
$percent_gouttext = 10;
$avatar_status_num;
$cover_status_num;
$profiletext = $display_profile['profile_text_approved'];
$sparetimetext = $display_profile['spare_time_text_approved'];
$travelintext = $display_profile['traveling_text_approved'];
$gouttext = $display_profile['go_out_text_approved'];
if($avatar_status_num == 2) { echo $percent_profile_image; } + if($avatar_status_num == 2) { echo $percent_profile_image; }
?>
Now I know my if code is wrong. What I would like to do if example $avatar_status_num = 2 i would like to print out 40. if $cover_status_num = 2 I would like to substract these to numbers so. 40 + 20. So it should only print out the number and substract it if the value from DB is nr2.
I hope you understand my question :)
Cheerz
Use an extra variable to sum your values.
$sum = 0;
if (isset($someValue) && $someValue == 2) {
$sum += 40;
}
if (isset($someOtherValue) && $someOtherValue == 2) {
$sum += 20;
}
Or if you wanna do this dynamically in your code:
$percent = array(
'profile_image' => 40,
'cover_image' => 20,
'profile_text_approved' => 10,
'traveling_text_approved' => 10,
'spare_time_text_approved' => 10,
'go_out_text_approved' => 10,
);
$sum = 0;
foreach ($display_profile as $key => $value) {
if (array_key_exists($key, $percent) && $value == 2) {
$sum += $percent[$key];
}
}
Note In this case the $percent key names should be the same as the $display_profile key names.

Convert my script in recursive way?

I have script who searches closest searched number.
So for example, let say that in array are this numbers:
'0' => 1.72
'0.25' => 1.92
'0.75'=> 2.35
'1' => 3.00
I am searching for 0.50 handicap, so 0.25 and 0.75 are in same range from 0.50.
In this situations i want to get greater number, what is 0.75 in this example.
Code what works is this:
function getClosest($search, $arr) {
$closest = null;
$num_arr = array();
$odd = 0.00;
$i = 0;
foreach ($arr as $handicap=>$item) { //first closest number
if ($closest === null || abs($search - $closest) > abs($handicap - $search)) {
$closest = $handicap;
$odd = $item;
}
else{
$num_arr[$handicap] = $item;
}
}
$newclosest = null;
$newodd = 0.00;
foreach($num_arr as $handicap=>$newitem){ //second closest number
if ($newclosest === null || abs($search - $closest) > abs($handicap - $search)) {
$newclosest = $handicap;
$newodd = $newitem;
}
}
//if difference between first and second number are same
if(abs($search - $closest) == abs($newclosest - $search)){
if($newclosest > $closest){ //if second number is greater than first
$closest = $newclosest;
$odd = $newodd;
}
}
return array('handicap'=>$closest,'odd'=>$odd);
}
I see that i can use recursion here, but i am not experienced in using recursion. I know that i need call it inside like this:
$rec_arr = getClosest($num_arr,$search);
but i get blank page even i dump function output.
use array_map function,
$data = array('0'=>1.72,'0.75'=> 2.35,'0.25'=>1.92,'1' => 3.00);
$v = 0.5; // search value
$x = null; // difference value
$y = array(); // temporary array
array_map(function($i)use($data,$v,&$x,&$y){
if(isset($x)){
if($x > abs($i-$v)){ // if difference value is bigger than current
$x = abs($i-$v);
$y = array($i=>$data[$i]);
}else if($x == abs($i-$v)){ // if difference value is same
$key = array_keys($y);
$y = $key[0] < $i ? array($i=>$data[$i]) : $y;
}
}else{ // first loop
$x = abs($i-$v);
$y = array($i=>$data[$i]);
}
},array_keys($data));
print_r($y); // result
output Array ( [0.75] => 2.35 ), hope this help you.
//$a is array to be searched
//$s is search key
//$prev_key and $next_key will be output required
$a = array('0'=>1,'0.25'=>123,'0.75'=>456,'0.78'=>456,'1'=>788);
$s = '0';
if(isset($a[$s])){
echo $s;
}
else{
reset($a);//good to do
while(key($a) < $s){
next($a);
}
$next_key = key($a);
prev($a);
$prev_key = key($a);
echo $prev_key.'-'.$next_key;
}
The above code uses array internal pointers. I think this may help you..
source: https://stackoverflow.com/a/4792770/3202287

If value is greater/lesser than xyz

I have a value as a number. For instance, 502.
I want to write a php if statement that will display some text if the value is lesser or greater than certain numbers, or between a range.
E.g.
number is 502, text will say: "Between 500-600"
number is 56, text will say: "Between 0-60"
etc.
So far I have this:
<?php $count=0;?>
<?php $board = getUserBoard($userDetails['userId']);?>
<?php if(is_array($board)):?>
<?php $boardCount = count($board);?>
<?php foreach($board as $key=>$value):?>
<?php
$boardPin = getEachBoardPins($value->id);
$count = $count + count($boardPin);
?>
<?php endforeach?>
<?php endif?>
And that gives me a number:
<?php echo $count;?>
I have tried writing...
<?php if(($count)): => 500 ?>
Over 500
<?php endif ?>
But I keep running into errors.
I'd like to create a list if possible with elseif statements denoting various number ranges.
E.g.
0-50, 51-250, 251-500 etc.
Can anyone help me?
Thanks.
The sanest, neatest and most widely used syntax for if conditions in PHP is:
if($value >=500 && $value <=600 )
{
echo "value is between 500 and 600";
}
if ($count >= 0 && $count < 100) {
echo 'between 0 et 99';
} elseif ($count < 199) {
echo 'between 100 and 199';
} elseif { ...
}elseif ($count < 599) {
echo 'between 500 and 599';
} else {
echo 'greater or equal than 600';
}
I wrote something like this a few years back (might be a better way to do it):
function create_range($p_num, $p_group = 1000) {
$i = 0;
while($p_num >= $i) {
$i += $p_group;
}
$i -= $p_group;
return $i . '-' . ($i + $p_group - 1);
}
print 'The number is between ' . create_range(502, 100) . '.';
It'll say 500-599, but you can adjust it to your needs.
I'm not sure what you need, but here is what I understand you ask:
function getRange($n, $limit = array(50, 250, 500)) { // Will create the ranges 0-50, 51-250, 251-500 and 500-infinity
$previousLimit = 0;
foreach ($limits as $limit) {
if ($n < $limit) {
return 'Between ' . ($previousLimit + 1) . ' and ' . $limit; //Return whatever you need.
}
$previousLimit = $limit;
}
return 'Greater than ' . $previousLimit; // Return whatever you need.
}
echo getRange(56); // Prints "Between 51 and 250"
echo getRange(501); // Prints "Greater than 500"
echo getRange(12, array(5, 10, 15, 20)); // Prints "Between 11 and 15"
function getRange($number){
$length=strlen($number);
$length--;
$r1=round($number,-$length);
if ($r1>$number){
$r2=$r1-pow(10,$length);
return ''.$number.' value is between '.$r2.'-'.$r1;
}
else {
$r2=$r1+pow(10,$length);
return ''.$number.' value is between '.$r1.'-'.$r2;
}
}
Try this.

For loop Logic Problems with PHP

This is my new code, its almost working, but I think my while loop is wrong some where?
Same as before, gets users taken sick puts it into a var. Then get users entitlement based on years of service, then work out what they have taken and see if the user has used all the full entitlement, then to see if they have used all there half pay entitlement.
Please Help?
if($this->CURRENT_USER['User']['role_id'] > 3) { //locks out user types
//Get Holidaytypes
$types = $this->Holiday->find(
'all',
array(
'conditions' => array(
'Holiday.holidaystype_id' => 3,
'Holiday.user_id' => $id
)));
//Get starting date
$contracts = $this->Holiday->User->Contract->find(
'all',
array(
'conditions' => array(
'Contract.user_id' => $id//$data['user_id']),
'order' => array('Contract.startson' => 'ASC')
)
);
//Get How Many sick days
foreach ($types as $key => $value) {
global $SickTotal;
$typesDataEnds = strftime ("%u-%d-%Y", $types[$key]['Holiday']['endson']);
$typesDataStarts = strftime ("%u-%d-%Y", $types[$key]['Holiday']['startson']);
$SickTotal = count($typesDataEnds - $typesDataStarts);
//echo $SickTotal;
//Get Contract Start & End Dates
$start = array_shift($contracts);
$end = array_pop($contracts);
$endDate = $end['Contract']['endson'];
$startDate = $start['Contract']['startson'];
if (empty($endDate)) {
$endDate = time('now');
}
if (!empty($startDate)) {
$SortEnd = strftime("%Y", $endDate);
$SortStart = strftime("%Y", $startDate);
$YearsService = $SortEnd - $SortStart;
if ($YearsService <= 1) {
$SetFullEntitlement = 5;
$SetHalfEntitlement = 5;
//echo 'one year';
} elseif ($YearsService >= 2) {
$SetFullEntitlement = 10;
$SetHalfEntitlement = 10;
//echo 'two years';
} elseif ($YearsService >= 5) {
$SetFullEntitlement = 20;
$SetHalfEntitlement = 20;
//echo 'up to five years';
} elseif ($YearsService > 5) {
$SetFullEntitlement = 30;
$SetHalfEntitlement = 30;
//echo 'five years or more';
} else {
$SetFullEntitlement = 0;
$SetHalfEntitlement = 0;
//echo 'no sick pay';
}
} else {
$YearsService = 0;
//echo 'Sorry No Start Date For You Found!';
}
while ($SickTotal > 0) {
if ($SetFullEntitlement != 0) {
$SetFullEntitlement--;
} elseif ($SetHalfEntitlement != 0) {
$SetHalfEntitlement--;
}
}
echo 'FullPay:';
echo $SetFullEntitlement;
echo '<br/><br/>Halpay:';
echo $SetHalfEntitlement;
echo $SickTotal;
}
debug($types);
die();
//$this->render('/artists/holidayslist');
}
}
If ($startdate <= 1 year) {
If that's literally what you've typed, it's not going to work. Maybe strtotime might make some sense of it?
In any case,
For ($i = $Totalsick, $i >= $Fulldays, $i--) {
For ($i = $Totalsick, $>= $Halfdays, $i--) {
you're missing an $i in there - you're evaluating nothing against $Halfdays. You're also using $i for two seperate loops, so they're both on the same counter. switch your second loop to use a different variable.
I'm not quite sure I follow exactly what you are trying to do here but you could tidy up your code a bit and save on lines of code. I assume that $startdate is how many years ago the user started.
$sickdays= array( 0=>5, 1=>10, 2=>20, 5=>30 );
$userdays= 0;
foreach ( array_keys( $sickdays ) as $years_service )
{
if ( $years_service <= $startdate )
$userdays=$sickdays[$years_service];
}
Now $userdays should be the correct number of paid sick days and half days ( the two are always the same in your example ) for this user. A simple comparison should be sufficient to check whether they have taken less or more than their allotted number of days and half days.
I haven't tried this as I'm not working with PHP today, so I'm sure someone will shoot me down directly, but by setting your variables once and writing fewer lines you should find your code gets easier to maintain.

php switch case statement to handle ranges

I'm parsing some text and calculating the weight based on some rules. All the characters have the same weight. This would make the switch statement really long can I use ranges in the case statement.
I saw one of the answers advocating associative arrays.
$weights = array(
[a-z][A-Z] => 10,
[0-9] => 100,
['+','-','/','*'] => 250
);
//there are more rules which have been left out for the sake of clarity and brevity
$total_weight = 0;
foreach ($text as $character)
{
$total_weight += $weight[$character];
}
echo $weight;
What is the best way to achieve something like this?
Is there something similar to the bash case statement in php?
Surely writing down each individual character in either the associative array or the switch statement can't be the most elegant solution or is it the only alternative?
Well, you can have ranges in switch statement like:
//just an example, though
$t = "2000";
switch (true) {
case ($t < "1000"):
alert("t is less than 1000");
break
case ($t < "1801"):
alert("t is less than 1801");
break
default:
alert("t is greater than 1800")
}
//OR
switch(true) {
case in_array($t, range(0,20)): //the range from range of 0-20
echo "1";
break;
case in_array($t, range(21,40)): //range of 21-40
echo "2";
break;
}
$str = 'This is a test 123 + 3';
$patterns = array (
'/[a-zA-Z]/' => 10,
'/[0-9]/' => 100,
'/[\+\-\/\*]/' => 250
);
$weight_total = 0;
foreach ($patterns as $pattern => $weight)
{
$weight_total += $weight * preg_match_all ($pattern, $str, $match);;
}
echo $weight_total;
*UPDATE: with default value *
foreach ($patterns as $pattern => $weight)
{
$match_found = preg_match_all ($pattern, $str, $match);
if ($match_found)
{
$weight_total += $weight * $match_found;
}
else
{
$weight_total += 5; // weight by default
}
}
You can specify the character range using regular expression. This saves from writing a really long switch case list. For example,
function find_weight($ch, $arr) {
foreach ($arr as $pat => $weight) {
if (preg_match($pat, $ch)) {
return $weight;
}
}
return 0;
}
$weights = array(
'/[a-zA-Z]/' => 10,
'/[0-9]/' => 100,
'/[+\\-\\/*]/' => 250
);
//there are more rules which have been left out for the sake of clarity and brevity
$total_weight = 0;
$text = 'a1-';
foreach (str_split($text) as $character)
{
$total_weight += find_weight($character, $weights);
}
echo $total_weight; //360
Much different ways to do this.
$var = 0;
$range_const = range(10,20);
switch ($var) {
case 1: $do = 5; break; # 1
case 2: $do = 10; break; # 2
case 3:
case 4:
case 5: $do = 15; break; # 3, 4, 5
default:
if ($var > 5 && $var < 10) { # High performance (6..9)
$do = 20;
} else if (in_array($var, $range_const, true)) { # Looks clear (10..20)
$do = 25;
} else { # NOT in range 1..20
$do = -1;
}
}
print($do);
There no direct range X..Y compares because $var checks to true in each step, but this allows do some nice cheating like this...
$in = create_function('$a,$l,$h', 'return $a>=$l && $a<=$h;');
$var = 4;
switch (true) {
case ($var === 1): echo 1; break;
case ($var === 2): echo 2; break;
case $in($var, 3, 5): echo "3..5"; break;
case $in($var, 6, 10): echo "6..10"; break;
default: echo "else";
}
If you have a more complex conditions, you can wrap them inside a function. Here's an oversimplified example:
$chartID = 20;
$somethingElse = true;
switch (switchRanges($chartID, $somethingElse)) {
case "do this":
echo "This is done";
break;
case "do that":
echo "that is done";
break;
default:
echo "do something different";
}
function switchRanges($chartID, $somethingElse = false)
{
if (in_array($chartID, [20, 30]) && $somethingElse === true) {
return "do this";
}
if (in_array($chartID, [20, 50]) && $somethingElse === false) {
return "do that";
}
}
I think I would do it in a simple way.
switch($t = 100){
case ($t > 99 && $t < 101):
doSomething();
break;
}

Categories