i want to sum all digit in a number - php

i want to add all digit in a number and if it is 11,22 then i want to display only 11 or 22 else i want to make it a single digit.
example 30=3+0=3
28=2+8=10=1+0=1
i just made a codebut it have an error
please help.
<?php
$day = 17;
$month = 8;
$year = 1993;
function sumday($day)
{
if ($day == 11)
{
$sday = 11;
}
elseif ($day == 22)
{
$sday = 22;
}
elseif ($day == 29)
{
$sday = 11;
}
else
{
do {
$nday = $day . "";
$sday = 0;
for ($i = 0; $i < strlen($nday); ++$i)
{
$sday += $nday[$i];
}
while ($sday <=9);
}
return $sday;
}

First of all I would suggest you to learn to separate the tasks that a function do.
You ask to sum up the digits of a number, you may first create a function called sum_digits
<?php
function sum_digits($num) {
if ($num < 10)
return $num;
return $num % 10 + sum_digits(floor($num/10));
}
and then via conditional do whatever you need to do.

please refer to unnikked's answer, that's a good answer.
And here's the full code, combined with unnikked's answer
<?php
$day = 17;
$month = 8;
$year = 1993;
function sumday($day)
{
if ($day == 11)
{
$sday = 11;
}
elseif ($day == 22)
{
$sday = 22;
}
elseif ($day == 29)
{
$sday = 11;
}
else{
$sday = $day;
do {
$sday = $sday % 10 + floor($sday/10);
} while ($sday >= 10);
}
return $sday;
}
?>
EDIT: If you want to return the sum if it's 11,22,33 in the while loop, then put the conditions in the while loop rather than using if else condition, it's much simpler tho :)
function sumday($day)
{
$sday = $day;
while ($sday >= 10 && $sday != 11 && $sday != 22 && $sday != 29){
$sday = $sday % 10 + floor($sday/10);
}
return $sday;
}
EDIT: here's the logic that can split the day and sum them
function sumday($day)
{
$sday = $day;
$arrday = str_split($sday); // split the day into array
$sumarrday = 0;
for($i = 0; $i < strlen((string)$sday); $i++){
$sumarrday = $sumarrday + $arrday[$i]; // sum the day from the array
}
$sday = $sumarrday;
// here you can modify the condition of while statement for your needs
// for example, if you want to return 29 when 29 shows up, add this to your condition, && $sday != 29
while ($sday >= 10){
$sday = $sday % 10 + floor($sday/10);
}
return $sday;
}

Try this:
else {
$nday = $day . ""; //moved out wrom loop
do {
$sday = 0;
for ($i = 0; $i < strlen($nday); ++$i)
{
$sday += $nday[$i];
}
$nday = $sday . ""; // you forget this line
while ($sday <=9);
}

Related

Fatal error: Call to undefined method DateTime::diff()

When my code is moved from local server to live server it shows an error like this :
Fatal error: Call to undefined method DateTime::diff()
Code:
<?php
date_default_timezone_set('Asia/Calcutta');
$sFinalDate = date('Y-m-d', strtotime($sDate));
$sNow = new DateTime();
$iRemain = new DateTime( $sFinalDate.$sTime);
$iInterval = $iRemain->diff($sNow);
$sTimeCounter = $iInterval->format("%h: %i :%s ");
$sCalculate = $iInterval->format("%a:%h:%i");
?>
Though I found a number of people who ran into the issue of 5.2 and
lower not supporting this function, I was unable to find any solid
examples to get around it. Therefore I hope this can help some others:
<?php
function get_timespan_string($older, $newer) {
$Y1 = $older->format('Y');
$Y2 = $newer->format('Y');
$Y = $Y2 - $Y1;
$m1 = $older->format('m');
$m2 = $newer->format('m');
$m = $m2 - $m1;
$d1 = $older->format('d');
$d2 = $newer->format('d');
$d = $d2 - $d1;
$H1 = $older->format('H');
$H2 = $newer->format('H');
$H = $H2 - $H1;
$i1 = $older->format('i');
$i2 = $newer->format('i');
$i = $i2 - $i1;
$s1 = $older->format('s');
$s2 = $newer->format('s');
$s = $s2 - $s1;
if($s < 0) {
$i = $i -1;
$s = $s + 60;
}
if($i < 0) {
$H = $H - 1;
$i = $i + 60;
}
if($H < 0) {
$d = $d - 1;
$H = $H + 24;
}
if($d < 0) {
$m = $m - 1;
$d = $d + get_days_for_previous_month($m2, $Y2);
}
if($m < 0) {
$Y = $Y - 1;
$m = $m + 12;
}
$timespan_string = create_timespan_string($Y, $m, $d, $H, $i, $s);
return $timespan_string;
}
function get_days_for_previous_month($current_month, $current_year) {
$previous_month = $current_month - 1;
if($current_month == 1) {
$current_year = $current_year - 1; //going from January to previous December
$previous_month = 12;
}
if($previous_month == 11 || $previous_month == 9 || $previous_month == 6 || $previous_month == 4) {
return 30;
}
else if($previous_month == 2) {
if(($current_year % 4) == 0) { //remainder 0 for leap years
return 29;
}
else {
return 28;
}
}
else {
return 31;
}
}
function create_timespan_string($Y, $m, $d, $H, $i, $s)
{
$timespan_string = '';
$found_first_diff = false;
if($Y >= 1) {
$found_first_diff = true;
$timespan_string .= pluralize($Y, 'year').' ';
}
if($m >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($m, 'month').' ';
}
if($d >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($d, 'day').' ';
}
if($H >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($H, 'hour').' ';
}
if($i >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($i, 'minute').' ';
}
if($found_first_diff) {
$timespan_string .= 'and ';
}
$timespan_string .= pluralize($s, 'second');
return $timespan_string;
}
function pluralize( $count, $text )
{
return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}
?>
source http://php.net/manual/en/function.date-diff.php
if you using php 5.3 then there would be another issue
working above example on php>=5.3

Why isn't count counting anything?

I'm having trouble making a simple count work. Right now 0 is constantly displayed when I run the code and I know it's because I set count to 0. But it should be displaying the number of times "Fizz" is displayed.
I'm sure it's simple but I just can't see what!
public function __construct($firstParam, $secondParam, $firstSound = "Fizz", $secondSound = "Buzz", $numbers = 100) {
$this->firstParam = $firstParam;
$this->secondParam = $secondParam;
$this->firstSound = $firstSound;
$this->secondSound = $secondSound;
$this->numbers = $numbers;
$this->numsArray = $numsArray;
}
public function __toString() {
$count = 0;
for ($i = 0; $i < count($this->numsArray); $i++){
$val = $this->numsArray[$i];
if ($val == $this->firstSound) {
$count++;
}
}
$print = "Number of Fizzes: ".$count;
return $print;
}
public function execute() {
$this->numsArray = array();
if ($this->secondParam > $this->firstParam) {
for ($i = 1; $i <= $this->numbers; $i++){
if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) {
$this->numsArray[] = "\n".$this->firstSound.$this->secondSound."\n";
} elseif ($i % $this->firstParam == 0) {
$this->numsArray[] = "\n".$this->firstSound."\n";
} elseif ($i % $this->secondParam == 0) {
$this->numsArray[] = "\n".$this->secondSound."\n";
} else {
$this->numsArray[] = "\n".$i."\n";
}
echo $this->numsArray[$i-1];
}
} else {
echo "\n".' First Number Bigger Than Second '."\n";
}
}
In your execute you are not assigning the values to numsArray[i] also you inject new line characters that will not match the equality you just when checking $val. Also I notice you use zero index to check them and index 1 to load it. Change execute to:
for ($i = 0; $i < $this->numbers; $i++){
if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) {
$this->numsArray[i] = $this->firstSound.$this->secondSound;
} elseif ($i % $this->firstParam == 0) {
$this->numsArray[i] = $this->firstSound;
} elseif ($i % $this->secondParam == 0) {
$this->numsArray[i] = $this->secondSound;
} else {
$this->numsArray[i] = $i;
}
echo $this->numsArray[$i];
This is a better binary string comparison for php...
if (strcmp($val, $this->firstSound) == 0)

For loop variable, confused about single and double quotes

I'd like to make the following code a for loop to make everything read better, but I can't seem to get the quotes right and end up with a blank page
if ($_POST['week'])
{
$week = $_POST['week'];
}
//or check for a value submitted by the week menu
elseif ($_POST["user_week1"] == "week1") {
$week = "1";
}
elseif ($_POST["user_week2"] == "week2") {
$week = "2";
}
else if ($_POST["user_week3"] == "week3") {
$week = "3";
}
else if ($_POST["user_week4"] == "week4") {
$week = "4";
}
else if ($_POST["user_week5"] == "week5") {
$week = "5";
}
else if ($_POST["user_week6"] == "week6") {
$week = "6";
}
else {
$week = "1";
}
I tried to do:
if ($_POST['week'])
{
$week = $_POST['week'];
}
for ($i = 1; $i<7; $i++)
{
else if ($_POST["user_week'.$i.'"] == "week'.$i.'") {
$week = $i;
}
}
else {
$week = "1";
}
But that didn't work out too well, I tried using double quotes instead of single around the variables, plus '" and "' to no avail.
Can anyone help with this, or point me towards a good resource on single and double quotes for variables?
Are you all igrnoring the fact that the else if mustn`t be there!?
What you should do is the following
$week = "1";
if ($_POST['week']) {
$week = $_POST['week'];
} else {
for ($i = 1; $i < 7; $i++) {
if ($_POST["user_week" . $i] == "week" . $i) {
$week = $i;
break;
}
}
}
elseif ($_POST['user_week' . $i] == 'week' . $i)
above correction should work

Separating an array effectively

I'm having an asbolute nightmare dealing with an array of numbers which has the following structure :
Odd numbers in the array : NumberRepresenting Week
Even numbers in the array : NumberRepresenting Time
So for example in the array :
index : value
0 : 9
1 : 1
2 : 10
3 : 1
Would mean 9 + 10 on Day 1 (Monday).
The problem is, I have a an unpredictable number of these and I need to work out how many "sessions" there are per day. The rules of a session are that if they are on a different day they are automatically different sessions. If they are next to each other like in the example 9 + 10 that would count as a single session. The maximum number than can be directly next to eachother is 3. After this there needs to be a minimum of a 1 session break in between to count as a new session.
Unfortunately, we cannot also assume that the data will be sorted. It will always follow the even / odd pattern BUT could potentially not have sessions stored next to each other logically in the array.
I need to work out how many sessions there are.
My code so far is the following :
for($i = 0; $i < (count($TimesReq)-1); $i++){
$Done = false;
if($odd = $i % 2 )
{
//ODD WeekComp
if(($TimesReq[$i] != $TimesReq[$i + 2])&&($TimesReq[$i + 2] != $TimesReq[$i + 4])){
$WeeksNotSame = true;
}
}
else
{
//Even TimeComp
if(($TimesReq[$i] != ($TimesReq[$i + 2] - 1))&& ($TimesReq[$i + 2] != ($TimesReq[$i + 4] - 1)))
$TimesNotSame = true;
}
if($TimesNotSame == true && $Done == false){
$HowMany++;
$Done = true;
}
if($WeeksNotSame == true && $Done == false){
$HowMany++;
$Done = true;
}
$TimesNotSame = false;
$WeeksNotSame = false;
}
However this isn't working perfectly. for example it does not work if you have a single session and then a break and then a double session. It is counting this as one session.
This is, probably as you guessed, a coursework problem, but this is not a question out of a textbook, it is part of a timetabling system I am implementing and is required to get it working. So please don't think i'm just copy and pasting my homework to you guys!
Thank you so much!
New Code being used :
if (count($TimesReq) % 2 !== 0) {
//throw new InvalidArgumentException();
}
for ($i = 0; $i < count($TimesReq); $i += 2) {
$time = $TimesReq[$i];
$week = $TimesReq[$i + 1];
if (!isset($TimesReq[$i - 2])) {
// First element has to be a new session
$sessions += 1;
$StartTime[] = $TimesReq[$i];
$Days[] = $TimesReq[$i + 1];
continue;
}
$lastTime = $TimesReq[$i - 2];
$lastWeek = $TimesReq[$i - 1];
$sameWeek = ($week === $lastWeek);
$adjacentTime = ($time - $lastTime === 1);
if (!$sameWeek || ($sameWeek && !$adjacentTime)) {
if(!$sameWeek){//Time
$Days[] = $TimesReq[$i + 1];
$StartTime[] = $TimesReq[$i];
$looking = true;
}
if($sameWeek && !$adjacentTime){
}
if($looking && !$adjacentTime){
$EndTime[] = $TimesReq[$i];
$looking = false;
}
//Week
$sessions += 1;
}
}
If you want a single total number of sessions represented in the data, where each session is separated by a space (either a non-contiguous time, or a separate day). I think this function will get you your result:
function countSessions($data)
{
if (count($data) % 2 !== 0) throw new InvalidArgumentException();
$sessions = 0;
for ($i = 0; $i < count($data); $i += 2) {
$time = $data[$i];
$week = $data[$i + 1];
if (!isset($data[$i - 2])) {
// First element has to be a new session
$sessions += 1;
continue;
}
$lastTime = $data[$i - 2];
$lastWeek = $data[$i - 1];
$sameWeek = ($week === $lastWeek);
$adjacentTime = ($time - $lastTime === 1);
if (!$sameWeek || ($sameWeek && !$adjacentTime)) {
$sessions += 1;
}
}
return $sessions;
}
$totalSessions = countSessions(array(
9, 1,
10, 1,
));
This of course assumes the data is sorted. If it is not, you will need to sort it first. Here is an alternate implementation that includes support for unsorted data.
function countSessions($data)
{
if (count($data) % 2 !== 0) throw new InvalidArgumentException();
$slots = array();
foreach ($data as $i => $value) {
if ($i % 2 === 0) $slots[$i / 2]['time'] = $value;
else $slots[$i / 2]['week'] = $value;
}
usort($slots, function($a, $b) {
if ($a['week'] == $b['week']) {
if ($a['time'] == $b['time']) return 0;
return ($a['time'] < $b['time']) ? -1 : 1;
} else {
return ($a['week'] < $b['week']) ? -1 : 1;
}
});
$sessions = 0;
for ($i = 0; $i < count($slots); $i++) {
if (!isset($slots[$i - 1])) { // First element has to be a new session
$sessions += 1;
continue;
}
$sameWeek = ($slots[$i - 1]['week'] === $slots[$i]['week']);
$adjacentTime = ($slots[$i]['time'] - $slots[$i - 1]['time'] === 1);
if (!$sameWeek || ($sameWeek && !$adjacentTime)) {
$sessions += 1;
}
}
return $sessions;
}
Here is my little attempt at solving your problem. Hopefully I understand what you want:
$TimesReq = array(9,4,11,4,13,4,8,4,7,2,12,4,16,4,18,4,20,4,17,4);
// First just create weeks with all times lumped together
$weeks = array();
for($tri=0; $tri<count($TimesReq); $tri+=2){
$time = $TimesReq[$tri];
$week = $TimesReq[$tri+1];
$match_found = false;
foreach($weeks as $wi=>&$w){
if($wi==$week){
$w[0] = array_merge($w[0], array($time));
$match_found = true;
break;
}
}
if(!$match_found) $weeks[$week][] = array($time);
}
// Now order the times in the sessions in the weeks
foreach($weeks as &$w){
foreach($w as &$s) sort($s);
}
// Now break up sessions by gaps/breaks
$breaking = true;
while($breaking){
$breaking = false;
foreach($weeks as &$w){
foreach($w as &$s){
foreach($s as $ti=>&$t){
if($ti>0 && $t!=$s[$ti-1]+1){
// A break was found
$new_times = array_splice($s, $ti);
$s = array_splice($s, 0, $ti);
$w[] = $new_times;
$breaking = true;
break;
}
}
}
}
}
//print_r($weeks);
foreach($weeks as $wi=>&$w){
echo 'Week '.$wi.' has '.count($w)." session(s):\n";
foreach($w as $si=>&$s)
{
echo "\tSession ".($si+1).":\n";
echo "\t\tStart Time: ".$s[0]."\n";
echo "\t\tEnd Time: ".((int)($s[count($s)-1])+1)."\n";
}
}
Given $TimesReq = array(9,4,11,4,13,4,8,4,7,2,12,4,16,4,18,4,20,4,17,4); the code will produce as output:
Week 4 has 4 session(s):
Session 1:
Start Time: 8
End Time: 10
Session 2:
Start Time: 11
End Time: 14
Session 3:
Start Time: 16
End Time: 19
Session 4:
Start Time: 20
End Time: 21
Week 2 has 1 session(s):
Session 1:
Start Time: 7
End Time: 8
Hope that helps.

Part of pascal function

I'm trying to rewrite a pascal program to PHP, and don't understand what this part of pascal function do:
while (u[3] <> 1) and (u[3]<>0) and (v[3]<>0)do
begin
q:=u[3] div v[3];
for i:=1 to 3 do
begin
t:=u[i]-v[i]*q;
u[i]:=v[i];
v[i]:=t;
{writeln('u',i,'=',u[i],' v',i,'=',v[i]); }
end;
end;
if u[1]<0 then u[1]:=n+u[1];
rae:=u[1];
Please help to rewrite it to PHP.
Thanks.
A very literal translation of that code, should be this one:
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 1 )
{
$q = floor($u[3] / $v[3]);
for ($i = 1; $i <= 3; $i++)
{
$t = $u[$i] - $v[$i] * $q;
$u[$i] = $v[$i];
$v[$i] = $t;
//writeln('u',i,'=',u[i],' v',i,'=',v[i]);
}
}
if ($u[1] < 0 )
$u1] = $n + $u[1];
$rae = $u[1];
Of course, u and v are arrays. Sorry for not giving any more info, but it's been like 10 years since Pascal and I last saw each other, but we had a profound romance for a long time, since I feel inlove for to hotties(C# and PHP) :)
while ($u[3] != 1) && ($u[3] != 0) && ($v[3] != 0) {
$q = floor($u[3] / $v[3]);
for ($i = 1; $i <= 3; $i++) {
$t = $u[$i] - $v[$i] * $q;
$u[$i] = $v[$i];
$v[$i] = $t;
echo "u$i={$u[$i]} v$i={$v[$i]}\n";
}
}
if ($u[1] < 0) {
$u[1] = $n + $u[1];
}
$rae = $u[1];
2 small corrections to David's code:
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 1 )
should be
while ($u[3] != 1 && $u[3] != 0 && $v[3] != 0 )
and
for ($i = 1; $i < 3; $i++)
i never reaches the value of 3
for ($i = 1; $i <= 3; $i++)
May be the Writeln can be translated to
echo 'u'.$i.'='.$u[$i].' v'.$i.'='.$v[$i];
When you do the translation of arrays, take into account that arrays in php uses 0 as the first index.
$u= array( 3, 5, 22 )
echo u[1]; // prints 5
while($u[3] != 1 && $u[3] != 0 && $v[3] != 0)
{
$q = ($u[3] - ($u[3] % $v[3]) ) / $v[3]; //just the same as floor($u[3]/$v[3]), but i want to use % here :)
for ($i = 1; $i <= 3; $i++)
{
$t = $u[$i] - $v[$i]*$q;
$u[$i] = $v[$i];
$v[$i] = $t;
echo '<br />u'.$i.'='.$u[$i].' v'.$i.'='.$v[$i];
}
}
if ($u[1] < 0) $u[1] = $n + $u[1];
$rae = $u[1];
I dont know pascal But i have tried :)
while ($u[3]!=1 && $u[3]!=0 && $v[3]!=0) [
$q=floor($u[3]/ $v[3]);
for ($i=1;$i<3;$i++) {
$t=$u[$i]-$v[$i]*$q;
$u[$i]=$v[$i];
$v[$i]=$t;
echo "u".$i."=".$u[$i]."v".$i."=".$v[$i];
}
if ($u[1]<0) {
$u[1]=$n+$u[1];
}
$rae=$u[1];
In php variable Name Start With $
No Begin End used here in php only braces :)

Categories