This question already has answers here:
Better way to add number to itself?
(9 answers)
Closed 5 years ago.
I'm wondering if this following piece of code makes sense from a PHP perspective:
if(isset($_POST['submit'])){
$year = $_POST['year'];
$month = $_POST['month'];
if($month == 'December'){
$month = 'January';
$year = $year + 1;//can this be done?
}
}
Sure. You could also do:
$year++;
or
$year += 1;
Yes, makes sense and is safe. The right side is evaluated first. There are shortcuts for these operations:
A = A op B
A op= B
So:
$year += 1;
And with everything else as well (-= *= /= .=). For incrementing a single unit, there is also $year++ or $year-- for decrementing, plus the variations ++$year and --$year.
Please check out the manual pages for Assignment Operators and Increment Operators.
Since you're using + operator you're telling php to mathematically sum both values, therefore both of them will be parsed as integer (or float) values before actually making the sum. So if $month's value is "10" (string), it will be parsed as 10 (integer) and then you will have 10 + 1 = 11.
Related
This question already has answers here:
Adding 2 to a variable each time
(5 answers)
Closed 1 year ago.
So I'm trying to make it so the computer counts up to ten by two and making a new line each time. When I tested this my entire computer crashed. What's wrong with it?
<?php
$test = 0;
while ($test < 10) {
$test + 2;
echo $test . "/n";
}
?>
Change:
$test + 2;
to:
$test += 2;
Currently, $test is always 0 in your code, since you are not assigning a new value to it, hence the infinite loop.
Additionally, you would also want to change:
echo $test . "/n";
to:
echo $test . "\n";
Since you need to use a backslash to indicate a new line character.
N.B. In PHP you can also use the PHP_EOL constant to indicate the end of a line.
Here you just sum $test with 2 but did not assign it back to $test
$test + 2;
Trying replace it by $test += 2;
Another point is /n is not "making a new line" as you expected, change it to \n instead.
Although you can use while statement, this is a good case to use for instead.
for($i=0; $i < 10; $i += 2)
{
echo $i . PHP_EOL;
}
Usually while is used to evaluate something every loop, some variable that can change inside the while, like a bool variable or an "infinite" loop until break.
When you have a already defined number of loops, for is usually a better approach.
So, I was wondering if anybody would mind checking over this task and correcting it? I'm very sure I've muddled Python in with what little PHP I know, and that there are open tags.
Basically, there'll be a field where the nasty decimal age goes ($age, which will later be replaced by the appropriate field id). Our site works in months for juveniles and then years and seasons for adults. Using the nasty age, I'm trying to calculate the rounded age values and then store them as a string value which will then be set as the value of the field that will display the age ($displayagefid, will be replaced later with the appropriate field id). Only certain usergroups will be updated (the list is huge, so I left it out).
I also have no idea how to set a variable as a string using both string and the value of another variable.
Please know that I'm a complete newbie to PHP.
This is intended to run as a task on a self-hosted MyBB forum.
Thank you in advance!
<?php
function task_age($task)
{
global $mybb, $db;
$increment = 0.04167
$age = $age + $increment
floor($age*4) = $seasons
floor($age) = $years
floor($age*12) = $months
if ($year < 1) {
$display_age = $months, "mnths"
}
elseif ( ! filter_var($year, FILTER_VALIDATE_INT) ){
$display_age = $year, "yrs"
}
else {
$display age = $display_age = $years, "yrs", $seasons, "s"
};
$query = $db->query("
UPDATE mybb_userfields userfields
for ($usergroup = a || b || d || all that other crap) {
SET $dispalyagefid = $display_age;
};
");
add_task_log($task, "The age characters task successfully ran.");
I had a cursory look over your code and the first thing which sticks out is you have some of your variable assignments back to front:
$increment = 0.04167
$age = $age + $increment
floor($age*4) = $seasons
floor($age) = $years
floor($age*12) = $months
Whatever is on the left gets set to whatever is on the right, so your first two are OK but the last three need switching around.
Having said that it seems to me you are not approaching this correctly. I enter my decimal age into your site but how are you going to work out seasons? It might be my birthday tomorrow, it might have been my birthday yesterday.
You would be better off having the user enter a date of birth, from that calculate their age.
$birthday=date_create("2013-03-15");
$today=date_create('now');
$diff=date_diff($birthday,$today);
Now in the $diff variable you can check all the elements of a PHP date. So first check if they are under 18:
if ($diff->format("%y") < 18) {
$ageInMonths = ($diff->format("%y") * 12) + $diff->format("%m");
$age = "$ageInMonths months";
}
If they are over 18 you want age in years, then calculate seasons from the remaining months.
else {
$ageInYears = $diff->format("%y");
$ageInSeasons = floor($diff->format("%m") / 4);
if ($ageInSeasons > 0) {
$age = "$ageInYears years and $ageInSeasons seasons";
} else {
$age = "$ageInYears years";
}
}
I'd like to add the following text to a page in Wordpress: "Gina is now in her 16th (or sixteenth) year at the company," where 16th is a calculation based on her start year.
I know how to calculate her number of years at the company using PHP echo:
<?php echo date("Y")-1998 ?>
I also know that there are functions that can be used to attach a suffix to the number, such as:
<?php
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
$abbreviation = $number. 'th';
else
$abbreviation = $number. $ends[$number % 10];
?>
What I don't know how to do is put these two things together and have them output properly on a Wordpress page. My knowledge of PHP is pretty basic so I'm hoping someone out here might have the answer. Thanks!
Well, you said the answer yourself, just put that code together:
<?php
$number = date("Y")-1998;
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
$abbreviation = $number. 'th';
else
$abbreviation = $number. $ends[$number % 10];
echo $abbreviation;
?>
Although I believe the base year would not be date("Y"), but some value fetched from wordpress about Gina.
This question already has answers here:
Find the missing and duplicate elements in an array in linear time and constant space
(8 answers)
Closed 8 years ago.
I am a newbie in PHP. I have been given the following as homework:
Write a php function called findMissing that receives 3 parameters. The function must
determine and return a missing number in an array of numbers – note: only one number will
be missing from the series of numbers, the number you must find. All the numbers will be
integers.
◦ $start : This will be an integer indicating the minimum number the array can contain.
◦ $end : This will be an integer indicating the maximum number the array can contain.
◦ $numbers : An array with numbers between $start and $end. This array might not
be sorted. There is no guarantee that the first or last number in the array will correspond
to $start and $end respectively. $start and $end are inclusive in the range of
numbers
As an example: findMissing(1, 5, array(2,5,1,3)); must return 4 as the
missing number. The array $numbers will always contain $end - $start number of
elements.
So far I have the following code:
function findMissing($start,$end,$numbers)
{
if ($start >0 && $end >0){
for ($x=0; $x<=end; $x++) {
$numbers=array($x);
}
}
foreach ($numbers as $value){
echo $value;
}
}
Please help because I am stuck
dude!! here is a simple solution for that
add all numbers between $start and $end as $sumAll
and also add all the elements of that array as $sum
now $missingNumber = $sumAll-$sum !!
Do it it would be fun :)
When you are faced with a problem, and this is not just for programming, first thing first is you have to picture the solution in your head and see it working.
Given this task a few ideas come to mind:
You can sort the array and loop through it, as soon as a number that's not equal to the previous number + 1 occurs, you can safely say that previous number + 1 is your missing number.
Another way you can solve this is by looping in the range of $start to $end and check if each value is in the given array with in_array(). As soon as you encounter a value that's not, needless to say, this is your number.
If your goal isn't to learn, but to just get rid of that homework, drop a comment I'll scribble the function for you.
You may try this
<?php
$start = 1;
$end = 5;
$numbers = array(2,5,1,3);
findMissing($start,$end,$numbers);
function findMissing($start,$end,$numbers)
{
$range[$start-1] = 0; // here, it will be $range[0] = 0;
for($i=$start; $i<=$end; $i++)
{
$range[$i] = $range[$i-1]+1;
if(!in_array($range[$i], $numbers))
{
echo '<br> Missing no= '. $i;
//return $i;
}
}
}
?>
Hope this will be helpful...
I have this code here...
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + $row['total'];
}
What it does, it takes the values of total and adds them up...but when I have values that are negatives, it adds them up as well for an example when I have -51.75 and -17.85 I get -69.60 which it should be -33.90 how do I fix this?
`-33.901 is the value I am expecting because when its two negatives I would like to subtract, not add
Thanks,
J
This might help:
(-51.75) + (-17.85) = -69.60
(-51.75) - (-17.85) = -33.90
Assuming you always need to add the second number regardless of it's sign, you need to take the absolute value by using the PHP abs function with $row['total']:
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + abs($row['total']);
}
In response to what you updated in your question:
-33.90 is the value I am expecting because when its two negatives I would like to subtract, not add
This is pretty much what using the abs function does. I could rewrite the above code snippet as:
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row) {
if ($remaining >= 0) {
$remaining = $remaining + abs($row['total']);
}
else {
$remaining = $remaining - abs($row['total']);
}
}
However, this does the exact same thing as simply using the PHP abs function, since you are always adding the magnitude of $row['total'] to $remaining.
again --> see php's abs() function if you want to add things and ignore the sign.
I am not sure what your question is exactly, but this would keep adding the absolute values if $remaining is negative until it is positive again.
$remaining = $remaining + ($remaining < 0 && $row['remainingbalance']
< 0 ? -1 : 1) * $row['remainingbalance']);
This works for your example, it would be 0 - 51.75 + 17.85 = -33.9. But I am not sure if it's the behavior you want in the bigger picture.