Reputation: 26341
How would I obtain the greatest value in an array if one of the array keys match a value in a string. For instance, the following results would be obtained.
$decenders=array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$string='ABC'; //results as 0
$string='ABCg'; //results as 4
$string='ABCgj'; //results as 5
Upvotes: 0
Views: 54
Reputation: 5151
How about this:
function getScore($haystack, array $descenders) {
// the initial score is 0, which will be used if no $descenders match
$highest = 0;
foreach($descenders as $needle => $score) {
//if the descender exists in the string and has a higher score, update the score
if(strpos($haystack, $needle) !== false) {
if($score > $highest) {
$highest = $score;
}
}
}
return $highest;
}
$descenders = array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$tests = array('ABC', 'ABCg', 'ABCgj');
foreach($tests as $test) {
var_dump(getScore($test, $descenders));
}
Output:
int(0)
int(4)
int(5)
Upvotes: 1
Reputation: 37365
I think easiest way (but not quickest) is to do like:
$decenders= array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>9,'y'=>4);
$sData = 'ABqC';
arsort($decenders);
$rgResult = array_intersect(array_keys($decenders), str_split($sData));
$iResult = count($rgResult)?$decenders[array_shift($rgResult)]:0;
//var_dump($iResult); //9
Upvotes: 2
Reputation: 212522
$decenders=array('Q'=>4,'g'=>4,'j'=>5,'p'=>4,'q'=>4,'y'=>4);
$string1='ABC'; //results as 0
$string2='ABCg'; //results as 4
$string3='ABCgj'; //results as 5
function getResult($decenders, $string) {
$result = array_intersect_key(
$decenders,
array_flip(
str_split($string, 1)
)
);
return (count($result) > 0) ? max($result) : 0;
}
echo $string1, ' => ', getResult($decenders, $string1), PHP_EOL;
echo $string2, ' => ', getResult($decenders, $string2), PHP_EOL;
echo $string3, ' => ', getResult($decenders, $string3), PHP_EOL;
Upvotes: 1
Reputation: 4616
This will split the string in single chars, iterate over them and will give you the greatest value.
$result = 0;
foreach(str_split($string) as $char) {
if(array_key_exists($char, $decenders))
if($decenders[$char] > $result)
$result = $decenders[$char];
}
echo $result;
Upvotes: 1