liquidacid
liquidacid

Reputation: 118

array search won't work with max($array) but works when defined

I have two arrays $yvalues and $xyvalues

this code returns an empty set for $matches.

$a= max($yvalues);// equals 200
function my_search($haystack) {
    global $a;

$needle=$a;

return(strpos($haystack, $needle)); 
} 


$matches = array_filter($xyvalues, 'my_search');
print_r($matches);    

This code works

 $a= max($yvalues);// equals 200
function my_search($haystack) {
//      global $a;

$needle='200';

return(strpos($haystack, $needle)); 
} 


$matches = array_filter($xyvalues, 'my_search');
print_r($matches);    

in my trial code what I have works which is why I'm asking for help.

$b= array('11','20','23','14','23');
$c =array('20,12','13,12','200,23','100,23');
$bmax = max($b);
//echo $bmax ."<BR>";
function my_search($haystack) {
    global $bmax;

    $needle =$bmax;

    return(strpos($haystack, $needle)); 
}

$matches = array_filter($c, 'my_search');
print_r($matches);
$tst = key($matches);

Upvotes: 0

Views: 44

Answers (1)

JustOnUnderMillions
JustOnUnderMillions

Reputation: 3795

Ok, you can to this

<?php    
#WORKING
$yvalues= array('11','20','23','14','23');
$xyvalues =array('20,12','13,12','200,23','100,23');
global $a;
$a = (string)max($yvalues);// equals 200
function my_search2($haystack) {
    global $a;
    $needle=(string)$a;
    return (bool)(strpos($haystack, $needle)!==false);
}
$matches = array_filter($xyvalues, 'my_search2');
print_r($matches);

#MODERN
print_r(array_filter($xyvalues, function($haystack) use ($yvalues){
    $needle = (string)max($yvalues);
    return (bool)(strpos($haystack, $needle)!==false);    
}));

Result: Array ( [2] => 200,23 [3] => 100,23 )

Points:

  • if you remove (string) from the $needle it will not work anymore

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character

  • if you want to savely generate an global var do global $a; first.

:-)

Upvotes: 2

Related Questions