Page 1 of 1

$creature = $thevar's sub-array name?

Posted: Wed Mar 19, 2008 12:06 am
by JAB Creations
I want to set $creature to equal the name of the sub-array that $thevar belongs to.

The array...

Code: Select all

<?php
$thevar = 'beagle';
 
$creatures = array
(
 'cats' => array // $creatures['cats']
 (
  'chausie',
  'ocicat'
 ),
 'dogs' => array // $creatures['dogs']
 (
  'beagle',
  'havanese'
 )
);
?>
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.

So if programmed right...
1.) if $thevar = 'beagle' then $creature would = 'dogs'
2.) if $thevar = 'chausie' then $creature would = 'cats'

Re: $creature = $thevar's sub-array name?

Posted: Wed Mar 19, 2008 12:55 am
by hawkenterprises
I'm going to attempt to do what I think you meant.

mixed array_search ( mixed $needle , array $haystack [, bool $strict ] )

Code: Select all

 
<?php
 
if(false !== array_search($thevar,$creatures['dogs'])){
    $creature = 'dog';
}
else{
    $creature = 'cat';
}
?>
 
There is no reason to check the other knowing that there is only two categories. You could of just as well used the cat sub array.

Re: $creature = $thevar's sub-array name?

Posted: Wed Mar 19, 2008 2:46 am
by JAB Creations
Whoa thanks for the spot-on answer! I wanted to make sure my question made as much sense to whoever read it and not just to me.

Not that I need it for the particular purpose I need it at hand for though would a for/each be needed if there were several sub-arrays to search through?

Thanks again! :mrgreen:

Re: $creature = $thevar's sub-array name?

Posted: Wed Mar 19, 2008 1:47 pm
by JAB Creations
I made a mistake! I did not realize that I posted an exact match question when I only wanted to find a relative match! I always get a true match unless $thevar is an exact match for a false match!

How do we modify the code then to have $thevar below match the dogs array with the exact same concept only doing relative matching ('the beagle' = beagle / dogs array where as 'we own a ocicat' = cat / cats array)?

$thevar = 'the dog is a beagle';