-3

I can echo the species and bone variables, but when I put then into the following code I get Notice: Undefined variable: species in <filename>. Any ideas?

  $species = $_GET['species'];
  echo $species ;

  $bone = $_GET['bone'];
  echo $bone ;

  function myfilter($row){
      return ($row['commonName']== $species && $row['elementName']==$bone);
  }
  $result = array_filter($data, 'myfilter');
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37

1 Answers1

0

Your approach is not going to make what you are trying to achieve. When you are using myfilter as a callback function for array_filter it will not get the variables outside that function.That's why species and bone variables are triggering Notice. You need to make the variables accessible from callback by using either the super global $_GET (that's not preferable by me ) or passing the species, bone in the callback in array_filter like below.

Using the super global

<?php

function myfilter($row){
      return ($row['commonName'] == $_GET['species'] && $row['elementName'] == $_GET['bone']);
  }
  
$result = array_filter($data, 'myfilter' );

Passing variables in callbacks

<?php

$species = $_GET['species'];
$bone = $_GET['bone'];

$result = array_filter($data, function ( $row ) use ( $species, $bone )
{
return ($row['commonName'] == $species && $row['elementName'] == $bone );
});
    
Al-Amin
  • 596
  • 3
  • 16