globally scoped variable not returning from function - php

I think I've been staring at this too long, but why won't $sum echo 23?
(I'm aiming to have a global scoped $sum injected in to a function and returned when the function is complete)
<?php
$sum = 0;
function find_divisible() {
for ($i = 0; $i < 10; $i++) {
if ($i % 5 == 0) {
echo "<br>".' $sum is equal to '.$sum.' and $i is equal to '.$i;
$sum += $i;
}elseif ($i % 3 == 0) {
echo "<br>".' $sum is equal to '.$sum.' and $i is equal to '.$i;
$sum += $i;
}else {
echo "<br/>$i is not divisible...";
}
}
return $sum;
}
find_divisible($sum);
echo "<br>";
echo $sum;
?>

So in your code you have 3 main errors/problems:
1. You forgot the following line in your function (at the top)
global $sum;
2. You return $sum, but you don't assign the function call to a variable, so you can remove it
3. You pass $sum as an argument to the function, but the function doesn't takes any arguments, so delete all parameters in the function call
But to archive your goal i see 3(4) different ways!
1. With global variables (Which you do now (But i wouldn't recommend that, because later you get really confused and encapsulation? you can forget that if you use global))
2. You can pass the variable as argument, your code would looks something like this:
$sum = 0;
function find_divisible($sum) {
//Code
return $sum;
}
$sum = find_divisible($sum);
echo $sum;
3. You can pass the variable by reference, your code would looks something like this:
$sum = 0;
function find_divisible(&$sum) {
//^ See here
//Code
}
find_divisible($sum);
echo $sum;
(4). You don't have to use any parameter if you say $sum is always 0 and you just return $sum and assign it to a variable, your code would looks something like this:
function find_divisible() {
$sum = 0;
//Code
return $sum;
}
$sum = find_divisible();
echo $sum;
(Hope this answer helps you, i think it's always good to see different ways/solutions)

You could pass the $sum as a reference like this:
function find_divisible(&$sum) {
// code here
}
But you wouldn't need to return it from the function. Any changes made to it in the function would be made to the original variable you passed into find_divisible($sum)

Just use the global keyword.
global $sum;
Although, I'd recommend taking it in as a parameter like so.
function find_divisible($sum) {
...
}

Related

How to sum numbers in a function's parameter and decrement second parameter until 0

I am new to php and I try to write a function that will return the sum of two numbers written in parameters. And every time it does the sum I want to decrement the second parameter until 0.
for example : sum(5,3) - it will return 11 (because 5+3+2+1=11)
How can I proceed?
This is my attempt so far:
<?php
function customSum($a, $b) {
if ($b == 0) { return $a; }
$sum=0;
for($x = $b; $x>0; $x--) {
$sum = $x + $sum;
}
return $sum + $a;
}
echo customSum(5, 3);
?>

Putting Incremental values in array

I have the following code
<?php
for ($i=1; $i<=4; $i++)
{
echo $i . "<br>";
}
?>
which Results 1 2 3 4
I have another code which have a variable $number = 1 and coding is as follows
if ($number = $i)
{
echo "Message" ;
}
MY issue is i need to check the variable $number(1) is available in the list of values displayed by variable $i.
Can anybody find a solution for that? Thanks in advance .
You should use == (comparison operator) instead of = to compare two values within an if statement, as follows:
if ($number == $i)
{
echo "Message" ;
}
However, assuming that it's just a typo, here is my suggestion:
You can store the numbers to be printed in an array first.
$i = array(1,2,3,4);
foreach($i as $num)
{
echo $num."<br/>" ;
}
Then, you can use the in_array() function of php to check if $number is present in any of the numbers printed above.
if(in_array($number, $i))
{
echo "Message" ;
}
try this this will put your incremental values in array and after that you can validate with any number
$inc=array();
for ($i=1; $i<=4; $i++)
{
array_push($inc,$i);
}
$number=1;
if(in_array($number, $inc))
{
echo "your Message" ;
}
= is the assigment operator, to compare you have to use ==
if ($number == 1) {
//...
}
Furthermore there are situatons where using
if ($number = $value) {
//...
}
is of use. this code would assign $value to $number and 'return' its value, therefore if ($number = 1) echo "hi"; will echo "hi" - while `if ($number = 0) echo "hi"; will output nothing. A assign like the above is quite useless, it is mostly used when you call a function, you want to restore its return value and compare it in the same step like
if ($number = getValue()) {
//$number is set to getValue() and is not 0, null or false
}

How to do PHP loops correctly

Write a class called math. It is to have one property called num. It also has one method (function) called factorial. This method is to start at 1 and multiply all of the integers to num. If num is 5 then you would multiply 1*2*3*4*5. Of course you are to do this in a loop.
Which loop should I use? For or do while? Also, do I need an inner loop?
I started with
For (i = 1; i <= 5; i++)
{
}
however, i'm stuck on what to do next...any suggestions?
You can do it using any loop. for loop can be converted to while and do .. while and opposite is true too.
for(i=0;i<5;i++)
is same as
i=0; while(i<5){i++;}
To to find the factorial you should multiply all the values from 1 to the number you want factorial of. So if $num = 5. Only one single loop is needed. You'd want to run this loop.
for($i=1;$i<$num;$i++){
$num*=$i;
}
I am not giving a full solution here because the question seems homework. If I give you full solution it will be spoon-feeding.
$result = 1;
$target = 5;
for ($i = 1;$ i <= $target; $i++)
{
$result *= $i;
}
echo $result;
or
$result = 1;
$target = 5;
while($target > 0) {
$result *= $target;
$target--; // You could do this all in one line, but for learners, this is clearer.
}
echo $result;
Each iteration you will want to multiply the total of the factorial by the value of $i
class Math {
public static function Factorial($factorial) {
$output = 1;
for($i = 2; $i <= $factorial; $i++)
$output *= $i;
return $output;
}
}
I've gotten to where I prefer the while(i--) loop:
<?php
class Math {
public $num = 0;
public function factorial() {
$result = 1;
$num = $this->num;
while ($num) {
$result *= $num--;
}
return $result;
}
}
$factor = new Math();
$factor->num = 5;
echo $factor->factorial();
?>
http://codepad.org/hUOgAoz2

Accessing class variables with for loop

I would like to access class variables with for loop, here is my simple class
class test{
public $var1 = 1;
public $var2 = 2;
public $var3 = 3;
public $var4 = 4;
}
$class = new test();
this is how i try to access variables with a loop
for($i = 1; $i <= 4; $i++){
echo $class->var.$i;
}
and i get error which says
Notice: Undefined property: test::$var in C:\xampp\htdocs\test\index.php on line 12
Well it's not really a big error and i actualy get the value echoed but i still don't understand why do i get this error?
also if i do it this way everything works fine:
echo $class->var1;
for($i = 1; $i <= 4; $i++){
$var = 'var' . $i;
echo $class->$var;
}
Or, as mentioned in the comments, this will work in newer versions of PHP
for($i = 1; $i <= 4; $i++){
$class->{'var' . $i}
}
You're not actually getting the value echoed, you're getting $i echoed.
echo $class->var.$i; is being interpreted as echo ($class->var).($i);. Since var isn't a variable (hence the error), it becomes echo ''.$i;, so you get the value of $i. It just so happens that var1 has the value 1. (Change $var1 to something else, and you'll see what I mean)
To fix the issue, you can do this:
for($i = 1; $i <= 4; $i++){
$class->{'var'.$i}
}
The stuff inside the {} is calculated first, so the correct property is read.
The code isn't doing what you think. It's only echoing 1-4 because of your $i in the for loop. If you were to change the vars in the class, your output will still be 1-4.
The undefined property notices is the clue: it is trying to access the property var.
If you want to store data that is repetitive and/or associated, especially like in your example, it is usually more suitable to store as an array:
class test{
public $vars;
public function __construct()
{
$this->vars = array(1, 2, 3, 4);
}
}
$obj = new test();
foreach($obj->vars as $var)
{
echo $var;
}
The dot (.) operator is getting used by the echo rather than the member call to $class.
One of many solutions:
for($i = 1; $i <= 4; $i++){
echo $class->{'var'.$i};
}
live example here
This already works fine on very recent PHP versions, but try this:
for($i = 1; $i <= 4; $i++){
$v = 'var'.$i;
echo $class->$v;
}

PHP: What's the difference between static variable inside a for loop and a non-static variable outside the for loop?

For example, what's the difference between
$foobar = 0
for ($i=0; $i<20; $i++) {
//do something using $foobar
$foobar++;
}
and
for ($i=0; $i<20; $i++) {
static $foobar = 0
//do something using $foobar
$foobar++;
}
???
Both of the above examples have different results than from the following:
for ($i=0; $i<20; $i++) {
$foobar = 0
//do something using $foobar
$foobar++;
}
All three variations have a different outcome. I understand that in the first of the three examples the value of the $foobar variable gets larger and larger and that in the third example the value of the $foobar variable gets reset during each loop. I'm not sure what's going on with the example using the static $foobar variable. It would seem that the first two examples should behave the same in the portion of the for loop where $foobar is used, but that is not the case for me.
For reference, here's my actual code (the algorithm is not complete yet). I've marked the for() loop that has me thinking about this topic:
function combine($charArr, $k) {
$currentsize = sizeof($charArr);
static $combs = array();
static $originalsize = "unset";
if ($originalsize === "unset") $originalsize = $currentsize;
static $firstcall = true;
if ($originalsize >= $k) {
$comb = '';
if ($firstcall === true) {
for ($i = $originalsize-$k; $i < $originalsize; $i++) {
$comb .= $charArr[$i];
}
$combs[] = $comb;
$firstcall = false;
}
if ($currentsize > $k) {
$comb = ''; //reset
for ($i=0; $i<$k; $i++) {
$comb .= $charArr[$i];
}
$combs[] = $comb;
//########### THE FOR LOOP IN QUESTION ###########
for ($i = $k-1; $i >= 0; $i--) {
static $range_adj = 0;
for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) {
if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) {
$comb = substr_replace($comb, $charArr[$j], $i, 1);
$combs[] = $comb;
}
}
$range_adj++;
}
if ($currentsize-1 > $k) {
array_splice($charArr, 0, 1);
combine($charArr, $k);
}
}
$output = array_values( $combs );
unset($combs);
return $output;
}
else {
return false;
}
}
If I remove the $range_adj variable from for loop and place it right before the said for loop as a none-static variable, then the result of my function is not the same. Here's what the modified for loop would look like:
$range_adj = 0;
for ($i = $k-1; $i >= 0; $i--) {
for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) {
if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) {
$comb = substr_replace($comb, $charArr[$j], $i, 1);
$combs[] = $comb;
}
}
$range_adj++;
}
The fact that I get two different outcomes leads me to believe that something is different with each method, because if the two methods produced identical results, then the outcome of my function would be the same in both scenarios, which is not the case when I test these scenarios. Why am I getting two results? Test my function out with both methods of the for loop implemented and you will also get varying results.
For your convenience, here's the original method:
for ($i = $k-1; $i >= 0; $i--) {
static $range_adj = 0;
for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) {
if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) {
$comb = substr_replace($comb, $charArr[$j], $i, 1);
$combs[] = $comb;
}
}
$range_adj++;
}
???
It seems to me that the results should be exactly the same, but they are not. If you run my function, you will notice that you get a different result with each method of the for loop.
The first and second loops appear to do the same thing. This is because, as with any other statically-initialized variable, static means you only initialize it once. It retains its value as you try to access it again. You'll find that the static $foobar will still exist outside the scope of the loop wherever you declare/initialize it; this is due to the nature of PHP and has nothing to do with the static variable.
The difference is made clear only when you attempt to access $foobar before the loop: it won't be declared yet in the second snippet because you only create it within the loop, so you may get an undefined-variable notice.
static $foobar = 0;
initializing once, other execute of static $foobar = 0 not do anything with $foobar variable
Above two prog have same output, but your last prog have variable which is reset during each loop.
when you use "Static" key word for any variable initialization then It retains untill you not destroy it.. or not destroy your program session.
You can use static in this fashion to prevent a variable from being reinitialized inside a loop.
in the first iteration if the static variable is not initialize then it would create it and keep it within the outer context, on every other iteration PHP Would just skip it as its already been initialized.
Both results prevail the same: http://codepad.org/evilks4R
The reason why it differs in your function is that your function is recursive which means the function combine calls combine from within itself, when taking out the static keyword on the second call of combine, the variable is being reinitialized thus making the results differ.
using the static keyword allows you to pass the arguments to the second call with there values that was produced in the third value.
here's an example of passing static members to the latter passes of a function call: http://codepad.org/gChjx7Om
if you had done:
$foo_bar = 0;
for(.....)
this would be within a function so that $foo_bar would get reset to 0 every time the function was called, therefore overwriting the last calls calculations.
if you moved the $foo_bar outside the function, and then where needed in the function you added:
global $foo_bar
you would have the same results.
http://www.cprogramming.com/tutorial/statickeyword.html

Categories