Undefined variable using function into function [duplicate] - php

This question already has answers here:
PHP variables in anonymous functions
(2 answers)
Closed 6 years ago.
I have an issue using this code in order to get the appropriate result.
My code:
function check_txt($url, $content) {
global $content;
$result = get_file_contents($url);
$arr = array_filter($result, function($ar) {
return ($ar['txt'] == $content);
});
return $arr[0];
}
I got this error when I execute the code:
Notice: Undefined variable: content in myfile.php
My question is how to pass content variable to function($ar) ? already tried function($ar, $content) and too global $content; like the code I posted.

You need to USE the $content variable assuming it is actually available, to make it available in your annonymous function
function check_txt($url, $content) {
$result = get_file_contents($url);
$arr = array_filter($result, function($ar) use ($content) {
return ($ar['txt'] == $content);
});
return $arr[0];
}
The Manual has more details and examples

Either
A) if you have $content previously defined in global scope, use the global you have and remove the $content parameter.
or,
B) remove the global declaration and pass something in using the $content parameter.
PS: As others have pointed out, you need to use a use() on the anon function... but also pass param or go global, don't do both.

The array_filter() function filters the values of an array using a callback function.
This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
http://www.w3schools.com/php/func_array_filter.asp
Hope this helps :)

Related

How to assign a variable outside php function [duplicate]

This question already has answers here:
Are PHP Variables passed by value or by reference?
(16 answers)
How to declare a global variable in php?
(10 answers)
Closed 3 years ago.
I would like to be able to assign the name of a variable outside the function so that the function can assign the chosen variable. It does not seem to work. Anyone have any ideas?
Below is my attempt, however the $admin variable is empty after running the function.
function assign_check($variable, $check) {
if (empty($_POST[$check])) {
$variable = "no";
} else {
$variable = $_POST[$check];
}
}
assign_check('$admin', 'admin');
My question is not about the use of global variables.
You can request a reference in the function body.
function assign_check(&$variable, $check) {
$variable = 'hello';
}
And call passing a variable (reference).
assign_check($admin, 'admin');
$admin value is now 'hello';
Fitting that to your code would result in
function assign_check(&$variable, $check) {
$variable = empty($_POST[$check]) ? "no" : $_POST[$check];
}
assign_check($admin', 'admin');
But returning a proper value would be much cleaner code than using references. Using a ternary operator like presented above would it even simplify without need of a function at all.
A normal way to assign the result of a function to a variable name specified outside the function would be to have the function return the result and assign it directly to the variable when you call the function.
function assign_check($check) {
if (empty($_POST[$check])) {
return "no";
} else {
return $_POST[$check];
}
}
$admin = assign_check('admin');
I would do it this way unless there was a compelling reason to do it otherwise.
For the specific type of thing it looks like this function is intended to do, I would suggest looking at filter_input.

Cannot call variable outside array_filter() [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
Why i cannot call variable outside array_filter(), this my code
class JsonSelect
{
public function jsonSource($jsonSource, $val){
$file_contents = file_get_contents($jsonSource);
if(!$file_contents){
throw new Exception('Invalid file name');
}
$json = json_decode($file_contents, true);
$q = $_POST['q'];
$filtered = $json;
if(strlen($q)) {
$filtered = array_filter($json, function ($key) use ($q) {
if (stripos($key[$val], $q) !== false) {
return true;
} else {
return false;
}
});
}
echo json_encode(array_slice(array_values($filtered), 0, 20));
}
}
and this my picture to describe my problem.
parameter $valcannot be called inside $key[$val]
The scope of the variables inside an anonymous function is ONLY within the anonymous function.
You need to inherit the variable from the parent scope.
You can find more details about it in the PHP Documentation about anonymous functions (Example #3)
which would transform this line:
$filtered = array_filter($json, function ($key) use ($q) {
into this:
$filtered = array_filter($json, function ($key) use ($q, $val) {
Add another variable in use:
$filtered = array_filter($json, function ($key) use ($q, $key) {
if (stripos($key[$val], $q) !== false) {
return true;
} else {
return false;
}
});
EDIT:
One of good explanations can be found here: https://teamtreehouse.com/community/variable-functions-vs-php-closures
...the benefit of a lambda is that it exists only as long as
the variable it is assigned to has a reference. So the way PHP manages
memory is by reference counting. Essentially, the PHP engine reads all
the files it needs in order to execute the program, and while doing so
it finds all the variables used and keeps a tally of how many times
they are used( reference count). While the script is being executed
each time the variable is used it subtracts one from the reference
count. Once the reference count hits zero, the variable is deleted
(more or less). Normally, a function is loaded into memory and stays
there for the entire execution of the script. However, a lambda can be
deleted from memory once the reference count of its variable hits
zero.
A closure on the other hand is an anonymous function that encapsulates
a part of the global scope at the time it is created. In other words,
you can pass a variable to a closure using the "use" keyword and that
variable's value will be the same as it was when the closure was
created regardless of what happen's outside the closure...
Basically use keyword is needed in order to created isolated scope for variables. Without it You wouldn't be able to inject any additional variable to the function.

Accessing parent function scope from anonymous function in PHP

I made this awesome plugin for wordpress to easily add references to blog posts using latex-like tags. It works really well, but there's one nasty detail: I'm using global variables, as I need to change a variable in an anonymous function of which I can't change the passed parameters (it's a callback function).
I tried the use syntax and it works but the variable gets copied into the anonymous function.
Here's the code, shortened to give a quick overview of what I want to do:
// Global variables, ugh...
// I don't want to declare $reflist here!
$reflist = array();
// Implementation of reference parsing.
function parse_references( $str ) {
// Clear array
$reflist = array();
// I want to declare $reflist here!
// Replace all tags
$newstr = preg_replace_callback( "/{.*}/",
function ( $matches ) {
// Find out the tag number to substitute
$tag_number = 5;
// Add to $reflist array
global $reflist;
// I don't want to have to use a global here!
$reflist[] = $tag_number;
return "[$tag_number]";
}, $str );
return $newstr;
}
So does anyone know how to solve this elegantly?
Pass the variable by reference with the use construct. This way, modifying the value of $reflist inside the anonymous function does have an external effect, meaning the original variable's value changes.
$newstr = preg_replace_callback("/{.*}/", function($matches) use (&$reflist) {
$tag_number = 5; // important ----^
$reflist[] = $tag_number;
return "[$tag_number]";
}, $a);

Associate return value to a function parameter (CALL BY REFERENCE) [duplicate]

This question already has answers here:
difference between call by value and call by reference in php and also $$ means?
(5 answers)
Closed 6 years ago.
I am wondering about returning value to a parameter instead of using =
example of "normal" way how to get return value
function dummy() {
return false;
}
$var = dummy();
But I am looking for a method how to associate return value without using =, like preg_match_all()
function dummy($return_here) {
return false;
}
dummy($var2);
var_dump($var2); //would output BOOLEAN(FALSE)
I am sure it has something to do with pointers but in preg_match_all() I never send any pointer to variable or am I mistaken?
preg_match_all('!\d+!', $data, $matches); // I am sending $matches here not &$matches
//I didn't know what to search for well it is simple CALL BY REFERENCE
It is CALL BY REFERENCE:
function dummy(&$var) { //main difference is in this line
$var = false;
}
dummy($var);
Use references
i.e.
function dummy(&$return_here) {
$return_here = false;
}
dummy($var2);
var_dump($var2);

Two different return types in PHP function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Multiple returns from function
Is it possible to return 2 results in the same PHP function? One is an array, the other is an integer. Could someone give me an example?
function functest() {
return array(1, "two");
}
list($first,$second) = functest();
There's nothing stopping you from returning whatever type you like from a function. You can return a dictionary with multiple keys, or an array of mixed object types, or whatever. Anything you like.
$arr = array();
$arr[] = $some_object;
$arr[] = 3;
$arr["a_string"] = "foo";
return $arr;
You have several options to simulate multiple return values (the first two, however, are just a kind of wrapping of multiple values into one):
Return an array with the two values: return array($myInt, $myArr); (see e.g. parse_url().)
Create a dedicated wrapper object and return this: return new MyIntAndArrayWrapper($myInt, $myArr);
Add an "output argument" to the function signature: function myFunc(&$myIntRetVal) { ... return $myArr; } (see e.g. preg_match(..., &$matches).)
What about this?
function myfunction() {
//Calculate first result
$arrayresult=...
//Calculate second result
$intresult=...
//Move in with each other . don't be shy!
return array($arrayresult,$intresult)
}
and in the other code
$tmp=myfunction();
$arrayresult=$tmp[0];
$intresult=$tmp[1];
It's totally possible since PHP doesn't use strong typing. Just return the value you want in whatever type you want. A simple example:
function dual($type) {
if ($type === 'integer')
return 4711;
else
return 'foo';
}
You can use several functions on the caller side to see which type you got, for example: gettype, is_int, is_a.

Categories