Add up array on button click php script - php

I have got this function in php that run and return a number. However what i want is the numbers to be add up each time the function is run.
Here is the code.
function sumRate(&$numbers) {
$sumArray="0";
if($numbers)
$sumArray=$numbers;
$countedArray=($sumArray+$numbers);
echo "<script>console.log('$countedArray')</script>";
}
example when button click Jquery Ajax sent the value to server side.
let say
sumRate("23");//console log 23
sumRate("20");//console log 20
but what I want is that each time the function is run console to log 43 instead of login each number
Weldone in advance

I'm not precisely sure of what your goal is, but if you would like to keep track of a running sum, one way is to use globals like so:
$sum = 0;
function sumRate($number) {
global $sum;
if($number) {
$sum += intval($number);
echo "<script>console.log('$sum')</script>";
}
}
sumRate("20");
sumRate("23");
Output:
<script>console.log('20')</script>
<script>console.log('43')</script>
Side note:
We cannot pass a value literal by reference. If we call sumRate("23") on a function with signature function sumRate(&$numbers), a fatal error will be thrown. Instead either pass in a variable, or omit the & from the signature.
Update:
On the client side if you would just like the final sum to be echo'd and not each number, then you can do this:
$sum = 0;
function sumRate($number) {
global $sum;
if($number) {
$sum += intval($number);
}
}
sumRate("20");
sumRate("23");
echo "<script>console.log('$sum')</script>";
Output:
<script>console.log('43')</script>

You will not see the input be added together because your input only lasts as long as the function call. You need a variable that can store this value, and is not limited to the scope of sumRate
Try
$mySum = 0;
sumRate($mySum, 23);//console log 23
sumRate($mySum, 20);//console log 43
function sumRate(&$sum, $number) {
if($number)
$sum +=$number;
echo "<script>console.log('$sum')</script>";
}

it'simple
<?php
function sumRate($numbers) {
global $countedArray;
$countedArray=$numbers+$countedArray;
return $countedArray;
}
echo sumRate(20);
echo sumRate(23);
?>

Related

Determining what a forloop must execute (and how many times) using an input variable

Is it possible make a forloop execute the code you've entered in a textbox on a html page?
I've tried doing this:
<?php
$codejwz = $_POST["codejwz"];
$aantalkeiren = $_POST["aantalkeiren"];
function forloop($aantalkeren, $code){
for($i=0; $i<$aantalkeren; $i++){
$code;
}
}
forloop($aantalkeiren, $codejwz);
?>
My input for "codejwz" was echo "test" and for "aantalkeiren" it was 40.
However, (to my surprise,) I didn't get any error messages. Just a blank page.
Could you help me out in this?
Thanks
Use eval() to execute code that's in a variable.
for($i=0; $i<$aantalkeren; $i++){
eval($code);
}
Use the create_function function to turn the $code into a function, then call the function in the loop.
Replace your loop and function call with this:
$innerFunc = create_function ("" , $codejwz);
for($i=0; $i<$aantalkeren; $i++){
$innerFunc();
}

Recursion function's variable value not changing in PHP

I want to print 1 to 10 numbers using recursion but its not working.
CODE
function table($num1) {
if( $num1 <= 10 ) {
echo $num1;
echo "<br>";
table($num1++);
}
}
$num = 1;
table($num);
Here's the error
Fatal error: Maximum function nesting level of '256' reached,
aborting!
But when I am declaring $num1 as global its working fine. Please anyone tell me the reason behind it.
table($num1++) means please pass $num1 to table(), and then increase it by one. So this is not what you want.
You have to write table(++$num1) instead. It means increase $num1 first, then pass it to table().
Because you are passing a variable in copy. So the first variable has still 1 for value, and you are calling infinitely your function "table".
By default, for all variables (with the exception of objects) PHP makes a copy when passing it to a function/method. If you want to pass the same "in-memory" variable, you have to do it by reference.
$myVar=1;
myFunction($myVar);
Before, you declared your function like this:
function myFunction(&myVar) { ...}
Regards
function table($num) {
if( $num <= 10 ) {
echo $num;
echo "<br>";
table(++ $num);
}
}
$num = 1;
table($num);
table(++ $num) means increase $num first then pass to table function
Try:
function table($value) {
echo $value;
echo "<br>";
$num1=$value+1;
if($num1<=10){
table($num1);
}
}
$num = 1;
table($num);

Auto increment a value when calling a function

How can I auto increment a value when calling a function? Here what I'm trying to do, and I need it just this way. Cant increment it any other way except when calling the function.
function makeyogurt($type = 1) {
echo "Quantity $type.\n";
makeyogurt($type++);
}
makeyogurt();
The code you've shown will necessarily lead to an infinite loop. I guess you are searching for the static keyword:
function fun() {
static $counter = 0;
$counter++;
echo "$counter";
}
If you use static inside a function/method definition, the variable will get created only the first time the function/method is called. It's value will be saved after the call and the variable will get initialized to that value in the next call.
Now you can call the function like this:
fun();
fun();
fun();
Output will be:
1
2
3
Check this manual page
$type++ is a so called post-increment, meaning it will be incremented after the value has been passed.
What you're looking for is ++$type, which is a pre-increment and will pass the newly incremented value.
Try this:
function makeyogurt($type = 1) {
echo "Quantity $type.\n";
$type += 1;
makeyogurt($type);
}
makeyogurt();
If you don't define $type outside the function it always will be 1. I'm not exactly sure what you want, but maybe this?
$type=1;
function makeyogurt($type = 1) {
echo "Quantity $type.\n";
global $type;
++$type;
}
makeyogurt(); //makes it 2
or this:
$type=1;
function makeyogurt($a = 1) {
echo "Quantity $a.\n";
++$a;
return $a;
}
$type=makeyogurt($type); //makes it 2

PHP how to reuse a function from a clean state

`I have a function called lets say calculate; what i want to do is run some loops with in the function calculating an outcome. at times this function does fail as it will get stuck in a loop, so iv got it covered to exit the loop but my problem is i want to restart this function and hope it come out with an outcome if not i will try again... on average the request does not have an outcome around 1 in 20, i need to restart the function from a clean slate.
i have tried to unset all the vars before i rerun the process with out success.please note this function will fail at times from the information handed to the process, un avoidable so
when this accurs i just want to rerun the function automatically to generate an outcome.
http://www.gamezslave.com/test/DynamicSlots.swf this is my test prototype give you an idea
sometimes you refresh it will error because of this factor.
<?php
$checker = 0; // if i cant get a result i could use this will tick up until condition
function shuffleArray($myArray) {
$value_count = array_count_values($myArray);
$last_value = $myArray[count($myArray) - 1];
unset($myArray[count($myArray) - 1]);
$shuffle = array();
$last = false;
while (count($myArray) > 0) {
$keys = array_keys($myArray);
$i = round(rand(0, count($keys) - 1));
while ($last === $myArray[$keys[$i]] ) {
$i = round(rand(0, count($keys) - 1));
echo "stuck";
$checker++;
if($checker>10){
echo " Too many checks so die, and restart process ";
return false;
bob; // this is the check function to goto and restart
}
}
$shuffle[] = $myArray[$keys[$i]];
$last = $myArray[$keys[$i]];
unset($myArray[$keys[$i]]);
}
if ($last_value === $last) {
$i = 0;
foreach($shuffle as $key=>$value) {
if ($value !== $last_value) {
$i = $key;
break;
}
}
array_slice($shuffle, $i + 1, 0, $last_value);
} else {
$shuffle[] = $last_value;
}
return $shuffle;
}
print_r(shuffleArray(array(1,5,5,3,7,7,7,7))); // just a example
function bob(){
if($checker>10){
$checker = 0;
shuffleArray();
echo "bob";
reset($myArray); // thought this may clean/reset the array i couldnt use
}
}
The idea this shuffle returns that no two symbols elemts of the same will be next to each other but sometimes at the end of the array as its shuffling randomly im left with bad odds (apple, orange, orange, orange) so what i need to do is resart this process again from start take in mind there is about 10 different item in the array and duplicates of each for example 10 apples ,10 oranges 4 bannanas 3 grapes sometimes the shuffle manages to generate an outcome where im stuck with too many of the same item at the end of the array wich then i need to rerun the script(and this bit is the problem) i dont know how.
Are you using globals?
If yes: Stop that. It's terrible practice. Seriously. There's never a reason to use globals with any sort of sane code.
If no: There's nothing to do. Each function invocation is a clean slate.
EDIT After seeing the code, I'm kinda speechless.
http://us3.php.net/manual/en/function.shuffle.php
I would set defaults to all variables inside of your function, and pass anything active as a parameter. Then use a set of return codes to indicate success or failure, or validate the outcome in some way and re-run.
I'm agreeing with Tyler Eaves here and i wanted to add as another reply a very important topic in programming:
A function "should" in theory be as scalar as possible meaning that it should not affect the outside world and should return the same information everytime for the same parameters.
If you call a function with parameter X, Y and Z and call it again while your system is in the same state, the function should return the exact same result.
But if a function is not scalar (Virtual for instance), such as dependant on external data (files, database rows or single instance accessible class data) then you should theorically not affect that external data from this function or else calling the function multiple times yield different results...

Variable Not Showing When Function Called Early In Script

Any help is appreciated. I cannot seem to get the value of $sum if I call showSum() before the function...
EXAMPLE 1: (this works fine)
[main code here]
$sum = $valueObtainedAfterWhileLoop;
function showSum(){
global $sum;
return $sum;
}
echo getSum();
EXAMPLE 2: (this does not work - no error is returned, but no value is printed to the screen)
echo getSum();
[main code here]
$sum = $valueObtainedAfterWhileLoop;
function showSum(){
global $sum;
return $sum;
}
I need to use the value of $sum at the top of the page. What can I do?
Absolutely nothing. The variable has not been assigned to yet, so there's no value to use. Try calculating it in the function instead.

Categories