Match in nested foreach using === and return?

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:

Match in nested foreach using === and return?

Post by JAB Creations »

This one is a doozy! I call a function with a given parameter ('audio'). I want to match the parameter $property (of a value of 'audio') to one of the "sets" of data (each set is divided by underscores).

Each set is then divided as variable/values by periods.

So I'm trying to match only and exactly (===) the $property to the variable and return it's value (return to stop the foreach loop from continuing).

To you an idea of the desired results...
echo example('audio') should echo '7'
echo example('backgroundimages') should echo 'z'
echo example('browserpatch') should echo '11'
echo example('chatroom') should echo '0'

I'm thinking off hand I could either do a partial preg_match and then just explode and return the value though that seems sort of cheap maybe? I wouldn't be asking these questions if I wanted the cheap way out though. :mrgreen: So I'm thinking maybe some sort of nested foreach loop with a === exact match. Gah...your thoughts please!

Code: Select all

<?php
function example($property)
{
 $cookie = 'audio.7_backgroundimages.z_browserpatch.11_chatroom.0_connection.0_css3.0_cursors.0';
 $pieces = explode('_', $cookie);
 foreach($pieces as $key=>$value)
 {
  $value = explode('.', $value);
  ${$value[0]} = $value[1];
   return $value[1];
 }
}
 
echo example('audio');
?>

(If you're following my critique thread you'll be pleasantly pleased by the lack of globals once I get this working :mrgreen:)
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: Match in nested foreach using === and return?

Post by JAB Creations »

I copied the key/value assignment for a relative array...doh!

Ok with that fixed and some modifications this works...

Code: Select all

function example($property)
{
 $cookie = 'audio.7_backgroundimages.z_browserpatch.11_chatroom.0_connection.0_css3.0_cursors.0';
 $pieces = explode('_', $cookie);
 foreach($pieces as $value)
 {
  $value = explode('.', $value);
  if($value[0]==$property)
  {
   return $value[1];
  }
 }
}
 
echo example('audio');
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Match in nested foreach using === and return?

Post by RobertGonzalez »

Are your cookies really going to be a massive string like that?
Post Reply