Page 1 of 1

Match in nested foreach using === and return?

Posted: Thu May 29, 2008 11:43 am
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:)

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

Posted: Thu May 29, 2008 12:30 pm
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');

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

Posted: Thu May 29, 2008 1:04 pm
by RobertGonzalez
Are your cookies really going to be a massive string like that?