Variable Not Showing When Function Called Early In Script - php

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.

Related

Unable to increment a global variable

I need a variable to be passed along several functions & if statements, i'm going to keep it short.
I start off with initializing a static counter which i will use to keep track of the case number in my mysql database;
static $counter = 1;
then i write my function in which i try to simply increment my global variable (this is in an if statement inside my function);
$counter++;
Now my code compiles and runs perfectly but the counter seems to never increment and give every case id 1.
Anyone know how i managed to mess this up?
EDIT (Current structure):
<?php
static $counter = 1;
function frontend($connection){
global $counter;
(...)
if(isset($_POST['submit'])){
(...)
if(isset($_POST['betaald'])){
$counter++;
}
}
} ...
Now this code makes a neat database of all i need except the counter which seems to be unchangeable.
Explain more about your code and see the example.
<?php
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "<br />";
}
keep_track();
keep_track();
keep_track();
?>
This will produce the following result −
1
2
3

PHP/Garbage collection, unsetting variable

Does anybody have an explanation to this weird behavior of php?
Basically, I made a variable $number, and than made a variable $num2, which is a ref to $number. So I thought they will both share the same memory location.
But when I unset $number, its still outputs .. , I thought that if I would use some gc commands it will clear it cause it looks like heap behavior. But it's still not working. :P
function sum(&$var) {
$var++;
}
$number = 5;
$num2 = &$number;
sum($number);
echo $number; echo '<br>';
gc_enable();
gc_collect_cycles();
sleep(5);
unset($number);
echo $num2;
In PHP when you unset a variable that another variable is referenced to (this is what occurs in your case), it simply breaks the link connecting those variables, but remains the value in the second variable.
This is described in the PHP docs.
$mainVar = "Hello!";
$linkedVar = &$mainVar;
unset($mainVar);
So even after $mainVar is unset, the $linkedVar retains that value.

Add up array on button click php script

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);
?>

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 Array issue when looping and echoing

I'm having trouble getting the array to work right, let me show you the code here
function scanArray(){
$al = sizeof($_userLoaders);
echo $al. "<br />";
for ($tr = 0; $tr <= $al; $tr++) {
echo "value: " .$tr. "<br />";
echo $_userLoaders[$tr];
}
}
//Fetch user's loaders.
$_userLoaders;
function get_user_loaders(){
$con = connectToMySQL();//connects to my_sql
mysql_select_db("my_database", $con);//connect database
$t = mysql_query("SELECT * FROM someTable
WHERE value_a=".$_SESSION['value_a']." AND value_b=someValue");
$x= 0;
//lets loop through the results and create an array to compare later.
while ($result = mysql_fetch_array($t)){
$_userLoaders[$x] = $result['value_c'];
$x++;
}
//lets get all the options for
print_r($_userLoaders);//this part prints what it should
scanArray();
}
okay, I minimized the code above to show you what's going on. Pretty much function get_user_loaders() works great. It fetches data from a table in a database, and returns what it should. Second, it makes an array out of it. Again, this part works great. When the print_r() method is called it prints what it should, here's an example of what it prints:
Array ( [0] => tableValue )
yes, at this point it only has one value, please note that this value can vary from no values to 100 values which is why I am using an array. In this case, i'm testing it with one value.
Now, once I call scanArray() It doesn't echo the values.
the scanArray() function echoes the following:
0
value:
so what I don't understand is why does it print it out, but it doesn't display the function? Thanks in advance.
Your problem is that $_userLoaders variable is declared outside the function and function scanArray knows nothing about it. You need to either pass that variable in as a parameter:
function scanArray($_userLoaders) {
...
}
with the call at the end being
scanArray($_userLoaders);
or alternatively declare the variable as global inside the function:
function scanArray($_userLoaders) {
global $_userLoaders;
...
}
That would be because $_userLoaders is not equal to anything inside your scanArray() function. While it's not good practice, you can add the line:
global $_userLoaders;
to your scanArray() function and every other function that uses that global variable then, and it should work.

Categories