I'm probably missing something simple here, but I have this function for finding the factors of a number.
function factor($n){
$factors_array = array();
for ($x = 1; $x <= sqrt(abs($n)); $x++)
{
if ($n % $x == 0)
{
$z = $n/$x;
array_push($factors_array, $x, $z);
}
}
return $factors_array;
}
I then want to do something like this...
factor(120);
print_r($factors_array);
This give me nothing though. Any ideas on where I'm going wrong?
You aren't assigning the variable to the return value of the function. As far as the PHP interpreter is concerned, $factors_array only exists if you're inside the factor() function. Try this:
$factors_array = factor(120);
print_r($factors_array);
Then you can reuse $factors_array in other areas of the code.
Have a look at this page for an explanation of why this happens.
just try this:
print_r(factor(120));
Because you can't access $factors_array; outside the function, this is called scope of variable, usually, variables that defined inside function are not available outside, also, variables that are defined outside function are not available inside function...
Read more Variable scope ΒΆ
Related
I have to do a function that returns a string at contrary to another variable. I have a problem.
<?php
$parolaAlContrario="";
function ribaltaStringa($nome){
$lenght=strlen($nome);
for($i=0;$i<$lenght+4;$i++){
$parolaAlContrario[$i]=$nome[$lenght-1];
$lenght=$lenght-1;
}
echo implode($parolaAlContrario);
}
ribaltaStringa("marco"); ?>
This code returns 'ocram'. I don't understand why if I put implode($parolaAlContrario) outside the function the result is the variable $parolaAlContrario empty. Why?
This is because the scope of your variable is outside of your function. You need to assign the variable to whatever the result is from the function.
You should make your function return the variable, and assign it when complete.
function ribaltaStringa($nome)
{
$lenght = strlen($nome);
$parolaAlContrario = array();
for($i = 0; $i < $lenght + 4; $i++) {
$parolaAlContrario[$i] = $nome[$lenght - 1];
$lenght = $lenght - 1;
}
return implode($parolaAlContrario);
}
Notice, instead of echoing the variable, I return the variable. This allows us to assign the result to your variable once the function is finished.
I've also defined the variable $parolaAlContrario inside the function right outside the loop, this will allow you to return the value.
When you call the function, you should assign the variable again.
$parolaAlContrario = ribaltaStringa("marco");
Likewise, you could make a completely new variable with the word reversed by just changing the name of the variable during declaration; E.G:
$newVariable = ribaltaStringa("marco");
Why make it simple if you can make it complicated? You don't need to write your own function for that. Just use PHP's built-in function strrev() which reverses a string and you can save it to a new variable if you want:
$parolaAlContrario = strrev('marco');
Try it out:
https://3v4l.org/RmdE1
I saw this on W3Schools.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
The output is 0, 1 and 2.
I wonder why it is not 0, 0 and 0.
Since each time the function is called, the variable x becomes 0 again.
I am a PHP beginner. Thanks!
If you declare a var static inside a function, the var keep it value over multiple calls. You could compare it to a static var inside of classes.
The code you post is a good example to see the actual effect. However I would only carefull use static inside functions, because most of the time, you need the static value somewhere else, reset the value, or something else which requires to much logic and makes the code really bad.
A good example would be a function, which returns a unique identifier for a given identifier. This could be simply achieved by using this code.
function unique_id($id) {
static $count = 0;
return $id . ($id++);
}
This example may clarify. static has a scope, thus is not a global variable. So I can define static $x outside the function and it will be defined there. Since static has scope, it wouldn't make any sense to keep on executing and resetting $x = 0. So, php will only acknowledge it the first time that line is called.
<?php
static $x = 1000;
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
<?php
function sum($y) {
$y = $y + 5;
}
$x = 5;
sum($x);
echo $x;
?>
So I have this code. The questions are: What does it output? The answer: 5. How do I make it to output 10? The answer: sum(&$x).
The problem is that I don't understand why the answer to the first question is 5. When you make sum($x), shouldn't it replace the function with $x, so $x= 5+5=10? Why the answer is 5? I really don't understand. Someone explaind me something related to pointers and the adress, but I didn't understand. I never understood the concept of pointers, and I googled it and apparently there are no pointers in php, so I'm super confused. My friend said that a variable is formed of a value, and the memory adress of that value. Can someone explain me like I'm 5 years old why the answer is 5 and not 10? Please
Let's pretend $x is a piece of paper with 5 written on it.
function sum($y) {
$y = $y + 5;
}
Here $y is the value of what you have written. You add 5 to such value in your mind, but the note is left untouched.
function sum(&$y) {
$y = $y + 5;
}
With the reference operator (&$y), you pass the very paper to the function, and it overwrites what's written on it.
For primitive values like numbers, I wouldn't bother and always return the value you want:
function valuePlusFive($x) {
return $x + 5;
}
$x = 5;
$x = valuePlusFive($x);
This is not a very good explanation from theory point of view, but this should help you understand the concept:
when you declare function like this and then call it:
function ($argument) {...}
The argument you pass there is passed by value. This means that inside the scope of a function you will be working with a copy of an argument you passed. You can imagine that before the function is called the copy of argument has been made and inside the function you're working with the copy, while original remains untouched. Once the function is finished the copy is no more
However when you declare it like this:
function (&$argument) {...}
You are passing argument by reference, meaning that you are working directly with a variable you've passed. So in this case no copies are made, you took the argument from one place, put it inside the function and changed it.
In PHP, "The scope of a variable is the context within which it is defined." (according to the docs). So inside your function, $y (a copy of the value you passed in) is being operated on, but it is not returned by the function. So when the function ends, the value is no longer accessible outside the function.
If you want to pass the variable in by reference (similar to a pointer in C) then you can add a & like so:
function sum(&$y) {
$y = $y + 5;
}
Now when you call this code:
$x = 5;
sum($x);
echo $x;
it will output 10. Maybe a better way to do this would be to return a value from your function, and output that value:
function sum($y) {
return $y + 5;
}
$x = 5;
echo sum($x);
Edit: Made more clearer
I have a problem with a variable disappearing between function calls
firstly I start here with $pid being an int taken from a JSON string
print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($pid);
I get the output 'PID12' which is how it should be
Next in the Algorithm::getpredictionForPlayer
static function getpredictionForPlayer($pid)
{
print "PID2: ".$pid."\n";
$points =0;
for ($i = 0; $i < 10; $i++)
{
print "algorithm: ".$pid."\n";
$points += v4::predictPointsForPlayer($pid);
}
return intval($points/10);
}
Occasionally i get 'PID2: 12', but more often all that prints is 'PID2: '
Is there a reason the variable would disappear during this time?
Your variable in the global scope is $pid yet you are passing $player_id into the function
print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($player_id);
You've then got a parameter in your static method called $pid
static function getpredictionForPlayer($pid)
but this isn't the same as the variable in your global scope. In fact this will take the same value as the $player_id that you are passing in. If you want the $pid variable from your global scope to exist in the static method you should pass it in instead of $player_id.
btw, you should think about whether you really need a static method. Generally they make things hard to test and should be avoided if possible. Should you have a player object and call the method getPrediction() on that?
Change this line:
$a['points'] = Algorithm::getpredictionForPlayer($player_id);
To this:
$a['points'] = Algorithm::getpredictionForPlayer($pid);
If you have an if statement like this:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
?>
Would you be able to access the $c variable outside of the if statement like so:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
echo $c
?>
In PHP, if doesn't have its own scope. So yes, if you define something inside the if statement or inside the block, then it will be available just as if you defined it outside (assuming, of course, the code inside the block or inside the if statement gets to run).
To illustrate:
if (true) { $a = 5; } var_dump($a == 5); // true
The condition evaluates to true, so the code inside the block gets run. The variable $a gets defined.
if (false) { $b = 5; } var_dump(isset($b)); // false
The condition evaluates to false, so the code inside the block doesn't get to run. The variable $b will not be defined.
if ($c = 5) { } var_dump($c == 5); // true
The code inside the condition gets to run and $c gets defined as 5 ($c = 5). Even though the assignment happens inside the if statement, the value does survive outside, because if has no scope. Same thing happens with for, just like in, for example, for ($i = 0, $i < 5; ++$i). The $i will survive outside the for loop, because for has no scope either.
if (false && $d = 5) { } var_dump(isset($d)); // false
false short circuits and the execution does not arrive at $d = 5, so the $d variable will not be defined.
For more about the PHP scope, read the variable scope manual page.
PHP's scope is completely function-based. It's not the same as C or Java where it's local to what block that variables are nested in.
For PHP's scope:
// Global variable
$a = 0;
function f()
{
// Cannot be accessed outside of f()
if (true)
$b = 0;
// However, it can still be accessed anywhere in f()
$b += 1;
}
If you want a variable to be global, simply use the global keyword:
// Global variable
$a = 0;
function f()
{
// Use $a from global scope
global $a;
// Modifies global $a
$a += 1;
}
function g()
{
// Use $b from global scope, even though it hasn't been defined yet
global $b;
// Can be accessed outside of g()
$b = 0;
// Cannot be accessed outside of g(); this $a "shadows" the global version
// The global $a is still 0
$a = 1;
}
If the if statement containing the variable was executed, then yes, you can access the variable outside of the if statement. Here's a thought on why it works that way. In many programming languages you can "declare" a variable before you use it, just to let the compiler know that it's there. For example in Java you can declare an 'int', then use it like so:
int number;
if(true)
number = 5;
In Java, you have to declare a variable like this before using it in an if-then statement. In php, however, there isn't really a way to do that. Since php is dynamically typed, you can't write int $number. In Java, the computer allocates a 32 bit block of memory (the size of an int) when the variable is declared. In php, I believe, the memory is not allocated until something is actually stored in the variable. The best equivalent to 'declaring' a php variable I could think of would just be to write:
$number; //This is NOT needed
if(true)
$number = 5;
But when you look at the code, it seems kind of strange to just write $number like that. I think the computer would think it was equally strange because as I said before, it is a dynamically typed language, and so it doesn't need to allocate a whole chunk of memory for the number. So you can just leave it like this:
if(true)
$number = 5;
Depends.
In PHP chances are yes it would, although of course, if a isnt < b, then c wont exist when you get to the echo c line and your code will complain.
However, in most languages this wouldnt compile for that reason