My PHP Function isn't working - php

I'm having trouble with the following code. What it should do is echo cats.php followed by example.php but it's not echoing the example.php. Any ideas why this might be happening?
$bookLocations = array(
'example.php',
'cats.php',
'dogs.php',
'fires.php',
'monkeys.php',
'birds.php',
);
echo $bookLocations[1];
function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}
findfile(0);

Try changing,
echo $bookLocations["$filenumber"];
to:
echo $bookLocations[$filenumber];
Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method to:
function findfile($filenumber, $bookLocations)
{
echo $bookLocations[$filenumber];
}

i believe you may also need to declare the global variable in your function.
global $bookLocations;

Ok, there are two issues.
Variable Scope
Your function doesn't know the array $bookLocations, you need to pass it to your function like so:
function findfile($filenumber, $bookLocations)
Array key
You don't want to wrap your array key in quotes:
wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];

The quotes in "$filenumber" turn your key into a string, when the keys to your array are all numbers. You are trying to access $bookLocations["1"] when in fact you want to access $bookLocations[1] -- that is to say, 1 is not the same as "1". Therefore, like others have said, you need to get rid of the quotation marks around the key (and check your variable scope too).

function findfile($filenumber)
{
global $bookLocations;
echo $bookLocations[$filenumber];
}
Good-style developers usually avoid global variables. Instead, pass the array to the function as the parameter:
function findfile($files, $filenum)
{
echo $files[$filenum];
}

$bookLocations is out of scope for your function. If you echo $filenumber you will see that it's in scope because you passed it in by value. However, there is no reference to $bookoLocations.
You should pass in $bookLocations
declaration: function findfile($filenumber, $bookLocations){
call: findfile(1, $bookLocations);
You could also to declare $bookLocations as global, but globals should be avoided if possible.

Related

Laravel Quick Question : $data->Day(variable here) how to use variable on this? [duplicate]

How can i reference a class property knowing only a string?
class Foo
{
public $bar;
public function TestFoobar()
{
$this->foobar('bar');
}
public function foobar($string)
{
echo $this->$$string; //doesn't work
}
}
what is the correct way to eval the string?
You only need to use one $ when referencing an object's member variable using a string variable.
echo $this->$string;
If you want to use a property value for obtaining the name of a property, you need to use "{" brackets:
$this->{$this->myvar} = $value;
Even if they're objects, they work:
$this->{$this->myobjname}->somemethod();
As the others have mentioned, $this->$string should do the trick.
However, this
$this->$$string;
will actually evaluate string, and evaluate again the result of that.
$foo = 'bar';
$bar = 'foobar';
echo $$foo; //-> $'bar' -> 'foobar'
you were very close. you just added 1 extra $ sign.
public function foobar($string)
{
echo $this->$string; //will work
}
echo $this->$string; //should work
You only need $$string when accessing a local variable having only its name stored in a string. Since normally in a class you access it like $obj->property, you only need to add one $.
To remember the exact syntax, take in mind that you use a $ more than you normally use. As you use $object->property to access an object property, then the dynamic access is done with $object->$property_name.

How to echo a function response in php

I created a function to check for special characters in a string, but I can't seem to get it to echo the response message
Here is my code
<?php
function chk_string($string){
if (preg_match('/[\^£$%&*()}{##~?><>|=_+¬-]/', $string))
{
$chk_str="false";
} else {
$chk_str="true";
}
return $chk_str;
}
$string="this is just a test" ;
chk_string($string) ;
echo $chk_str;
?>
The "echo $chk_str" is not echoing anything.
If you did
$chk_str = chk_string($string);
then you could echo $chk_str;.
The $chk_str you are trying to echo is only visible in your function.
More description:
Your function (chk_string) is in a different scope than your echo.
Your function returns a variable, but that variable is "lost", since you don't assign it to another variable.
Your code currently does something like this line by line:
Your function declaration
$string means "this is just a test"
your functions result as a string, just floating in the code
write out a variable that doesn't exist.
I hope this helped in someway.
You need to store returned value in a particular variable if you want to echo that variable like this,
$chk_str = chk_string($string) ;
echo $chk_str;
Another way you can just directly echo returned value like this,
echo chk_string($string) ;
Your question is about variable scope and it is answered already, but I would recommend you to take a look at variable scope here https://www.php.net/manual/en/language.variables.scope.php.
Basically, every variable has its scope and we can not access a variable outside its scope. In your case, scope of variable $chk_str is inside function chk_string so you can not access it outside of the function. Because you return value of $chk_str in function chk_string so you still can access its value through response of function chk_string, for example:
echo chk_string('a string');
OR
$result = chk_string('a string');
echo $result;

PHP 5.4 Anonymous Function in Array undefine

This is PHP 5.4 code...
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function(){return abc($YesNo);});
echo $x['active']();
?>
Notice: Undefined variable: YesNo on line 7
Output Should be : Yes
if i directly put array in code by replace $YesNo like
<?php
function abc($YesNo){return $YesNo["value"];}
$x = array("active"=>function(){return abc(array("value"=>"Yes","text"=>"Yes"));});
echo $x['active']();
?>
output : Yes
which is correct output. Now what's the problem in first code. I need that for re-usability
Try this,
You can use use for passing data to a closure.
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
echo $x['active']();
?>
You provide your anonymous function with a parameter:
$x = array("active"=>function($param){return abc($param);});
then you call it:
echo $x['active']($YesNo);
You may use the use keyword to make your function aware of an external variable:
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
but it would be quite against the idea of reusability, in this case.
The problem is that your variable is not accessible within the function due to Variable Scope.
Because the array is defined outside of the function, it is not by default available inside the function.
There's a couple of solutions
Disclaimer: These are intended to fit within the scope of the question. I understand that they are not necessarily best practice, which would require a larger discussion
First Option:
You can declare the array within the function, like below. This is useful if you don't need access to it outside of the function.
function abc($YesNo){
$YesNo = array("value"=>"No","text"=>"No");
return $YesNo["value"];
}
Second Option:
Within your abc function, you can add the line global $YesNo. This is useful if you do need access to the array outside of the function:
function abc($YesNo){
global $YesNo;
return $YesNo["value"];
}
Other options exist (such as moonwave99's answer).
Finally:
Why are you putting an anonymous function within the array of $x? Seems like a path that will lead to problems down the road....
Your variable $YesNo needs to be visible in the scope of your anonymous function. You need to add global $YesNo as the first statement in that function:
So
$x = array("active"=>function(){return abc($YesNo);});
becomes
$x = array("active"=>function(){global $YesNo; return abc($YesNo);});
... also "value"=>"No" should be "value"=>"Yes" if you want it to return "Yes"

PHP - set a variable which does not neet to call using global

I have a variable called
$variable
And when I call it inside a function then I need to use
some_function(){
global $variable;
echo $variable['array'];
}
But I dont want to use a global every time, Is there a way so by which I can call variable without setting a global everytime???
Thanks for your time.
standard practice ...
some_function($variable){
echo $variable['array'];
}
called like any other function:
some_function($variable);
You can Pass it as a parameter to your function
$variable=array(2,5,6,9,7);
some_function($param){
print_r($param); // this is your variable
}
call it like
some_function($variable);
In case you don't want to use "global", you may use $GLOBALS superglobal variable:
function some_function() {
echo $GLOBALS['variable']['array'];
}
$GLOBALS is an associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
http://www.php.net/manual/en/reserved.variables.globals.php

Unexpected behaviour with variable variables

I was trying to pass a variable that contained the name of the superglobal array I wanted a function to process, but I couldn't get it to work, it would just claim the variable in question didn't exist and return null.
I've simplified my test case down to the following code:
function accessSession ($sessName)
{
var_dump ($$sessName);
}
$sessName = '_SERVER';
var_dump ($$sessName);
accessSession ($sessName);
The var_dump outside of the function returns the contents of $_SERVER, as expected. However, the var_dump in the function triggers the error mentioned above.
Adding global $_SERVER to the function didn't make the error go away, but assigning $_SERVER to another variable and making that variable global did work (see below)
function accessSession ($sessName)
{
global $test;
var_dump ($$sessName);
}
$test = $_SERVER;
$sessName = 'test';
var_dump ($$sessName);
accessSession ($sessName);
Is this a PHP bug, or am I just doing something wrong?
PHP: Variable variables - Manual
Warning
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
Solutions
function access_global_v1 ($var) {
global $$var;
var_dump ($$var);
}
function access_global_v2 ($var) {
var_dump ($GLOBALS[$var]);
}
$test = 123;
access_global_v1 ('_SERVER');
access_global_v2 ('test');
From php.net:
Warning
Please note that variable variables cannot be used with PHP's
Superglobal arrays within functions or class methods. The variable
$this is also a special variable that cannot be referenced
dynamically.
The answer is fairly simple: never use variable variables.
Use arrays instead.
(and yes - you are doing something wrong. No, it is not a bug in PHP.)
Use $GLOBALS. There you go :)
<?php
function accessSession ($sessName)
{
var_dump ($GLOBALS[$sessName]);
}
$sessName = '_SERVER';
accessSession ($sessName);

Categories