1

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.

Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39
Brave Type
  • 165
  • 1
  • 2
  • 7

3 Answers3

2

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

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

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.

0

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 :)

Aravind Pillai
  • 739
  • 7
  • 21