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
Related
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();
?>
I wanted to know whether i can pass a globally defined variable within a function parameter value. e.g.
$tweetsdisplayed = 40;
function display_latest_tweets(
$twitter_user_id,
$cache_file = './tweets.txt',
$tweets_to_display = $tweetsdisplayed)
{
Currently, the option above is not working, even when i dont pass it as a variable tweetsdisplayed. Whats the best way of doing this?
Thanks in advance
PHP Manual says:
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
but you can use $_GLOBALS.
e.g.:
$tweetsdisplayed = 40;
function display_latest_tweets(
$twitter_user_id,
$cache_file = './tweets.txt',
$tweets_to_display = null)
{
$tweets_to_display = isset($tweets_to_display) ? $tweets_to_display : $_GLOBALS['tweetsdisplayed'];
}
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 ΒΆ
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);
I have this line in a class function:
$this_value = eval("return $$existing_value;");
This gives me the value I need when the $$existing_value variable is set in the function, but I've found that I actually need to access the global scope in 99% of cases. I've tried rewritting it as $this_value = eval("return global $$existing_value;");, but that returns a php error.
Does any know how I can do this correctly?
(by the way, I am aware of the poor pratice this represents - but given the situation I cannot think of any other approaches)
Try
$this_value = eval('global $existing_value; return $$existing_value;');
or
$this_value = eval('global $$existing_value; return $$existing_value;');
$x = 3;
function sss()
{
$x = 1;
$y = eval('global $x; return $x;');
var_dump($y);
}
sss();
Will output int(3) , so it works , but be carefull about double quotes and simple quotes!
Since eval is returning the value you need, you should be bale to just assign the return value to the $_GLOBAL or $_SESSION (preferred because $_GLOBAL is evil) super globals.
$foo['bar'] = "pie";
$fixed_name_variable = "foo['bar']";
$_GLOBAL['foo'] = eval("return $$fixed_name_variable;");
echo $_GLOBAL['foo']; // pie
I've been re-thinking this process. I have relised that I can add a new array with a fixed name which the various processes contributing to this function can add the values needed, programatically, rather than trying to guess at names.
It'll also be far more secure and reliable than variable variables.