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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

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

Post 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'
User avatar
hawkenterprises
Forum Commoner
Posts: 54
Joined: Thu Feb 28, 2008 9:56 pm
Location: gresham,oregon
Contact:

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

Post 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.
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

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

Post 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:
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

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

Post 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';
Post Reply