Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'function' and 'use' and 'array_filter' work in PHP?

I am familiar with creating a PHP function placed at the top of the .php file such as:

function my_little_function($parm1,$parm2) {
   if ($parms < $parm2) {
   return "yes";
   } else {
   return "no";
   }
}

Then call it like this:

$result = my_little_function("1","2");
echo "The answer is $result." . "\n";

I have some code, I didn't write it, which uses "function" and "use" together inside of a traditional use of a function like my_little_function above.

I'm puzzled by this and have some questions for you more experienced PHP developers. Here is part of the working PHP code I'm referring to:

$neededObject = array_filter($st_ny_trip->STOPS->STOP,function($e) use ($final_desired_dest,$connect_raw){return $e->NAME == $final_desired_dest && DateTime::createFromFormat("m/d/Y g:i:s a", $e->TIME) > $connect_raw;});

$e is not set in any part of the function or the rest of the program, so what is using $e? How does it get passed a value and how is it being used? There appears to be no name for this function, so I don't know how it is being called, how is that being done?

Is this creating a function, on-the-fly to be used and it gets re-generated each time this code gets called? If it's a function, why not create it outside of this function and call it?

I've also not used 'use' myself yet, so that's unfamiliar to me. I looked it up on php.net and it just looks like a way to assign a value to something, but I couldn't find any practical examples to demonstrate why it's needed and when it should be used.

I looked up array_filter and it says it's "Filters elements of an array using a callback function". I don't know what a call back function is. Is it referring to function($e)?

Should the above line of PHP code for $neededObject be formatted differently so it is easier to read?

like image 922
Edward Avatar asked Aug 12 '13 08:08

Edward


People also ask

What is array_filter function in PHP?

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.

What does Array_splice () function do give an example?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

How do you filter an array key?

Filtering a PHP array by keys To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.


2 Answers

Let's use array_map() to explain what's going on.

We want to duplicate the input of an array: so if the input is aa, the output would be aaaa.

So the normal way, would be to create a function and then pass it to array_map():

$array = range('a', 'e');

$new_array = array_map('duplicate', $array);
print_r($new_array);

function duplicate($string){
    return $string.$string;
}

Online demo

But what if you want to use this function only once ? Since PHP 5.3, there is something called anonymous functions, we use it like the following:

$array = range('a', 'e');

$new_array = array_map(function($string){
    return $string.$string;
}, $array);
print_r($new_array);

Online demo

Now, let's say for example you want to add a standard value from another variable. That's easy with global variables. But as we know, global variables are evil and should be avoided. We may use use():

$array = range('a', 'e');
$standard_value = ',';

$new_array = array_map(function($string)use($standard_value){
        // $standard_value becomes available inside the function
    return $string.$standard_value.$string;
}, $array);
print_r($new_array);

Online demo

use() can be become also useful if we use a reference to write to an external variable while looping:

$array = range('a', 'e');
$another_string = '';

$new_array = array_map(function($string)use(&$another_string){// note &
    $another_string .= $string.$string; // overwrite $another_string
    return $string.$string;
}, $array);
print_r($new_array);
echo PHP_EOL . $another_string;

Online demo

like image 64
HamZa Avatar answered Sep 28 '22 06:09

HamZa


the $e variable acts as a normal function parameter, and will thus be passed by the code calling the function, see the documentation for the value of $e when using array_filter.

The use statement imports variables from the local scope into the anonymous' function's scope.

$myvar = 'world';
$myFunc = function ($test) use ($myvar) {
    return $test . ' ' . $myvar;
};
echo $myFunc('hello'); // echoes 'hello world';

If you did not include the use ($myvar) part, then isset($myvar) would return false from inside the anonymous function, since it has a separate scope.

like image 30
NDM Avatar answered Sep 28 '22 08:09

NDM