Forum Moderators: coopster

Message Too Old, No Replies

Partial match var against sub-array?

Get the name of the sub-array that a variable partially matches?

         

JAB Creations

7:00 pm on Mar 19, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How do I set $creature to equal the name of the sub-array that $thevar partially matches?

The Array

<?php
$thevar = 'We own a beagle who eats a lot of food.';

$creatures = array
(
'cats' => array // $creatures['cats']
(
'chausie',
'ocicat'
),
'dogs' => array // $creatures['dogs']
(
'beagle',
'havanese'
),
'deer' => array // $creatures['deer']
(
'moose',
'pudú'
)
);
?>

I'd like to set $creature to equal the name of the sub-array which is either equal 'cat' or 'dog' in this example based on which group $thevar matches.

Remember I want to do a partial match not an exact match.

So if programmed right...
1.) if $thevar = '123beagle456' then $creature would = 'dogs' (found in the dogs sub-array)
2.) if $thevar = '123chausie456' then $creature would = 'cats' (found in the cats sub-array)
3.) if $thevar = '123pudú456' then $creature would = 'deer' (found in the deer sub-array)

- John

mooger35

7:35 pm on Mar 19, 2008 (gmt 0)

10+ Year Member



I'm sure there is a better way but this works:

$creatures_new = array();
foreach($creatures as $key => $val){
foreach($val as $subkey => $subval){
$creatures_new[$subval] = $key;
}
}
foreach($creatures_new as $subanimal => $animal){
if(preg_match("/$subanimal/i",$thevar)){
$creature = $animal;
}
}
echo $creature;

JAB Creations

8:03 pm on Mar 19, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks Mooger, that works great!

- John