0

supposing I have an array like the one below:

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Group1
            [description] => This is the group1.
        )

    [1] => Array
        (
            [id] => 2
            [title] => Group2
            [description] => This is group2.
        )

)

Supposing the title is known as "Group2". How would I able to determine using PHP its equivalent description (that is "This is group2") if it doesn't have any idea of its ,key,id, etc. only the title?

Thanks for any help.

1
  • 2
    Loop through the array and check if the title key is Group2, if so simply get the description Commented Feb 22, 2013 at 8:53

3 Answers 3

3

Try this :

$title = "Group2";

foreach($your_array as $val){
   if($val['title'] == $title){
      echo $val['description'];
      break; //cut back on unnecessary looping
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try like this

foreach($myarray as $val){
  if($val['title'] == "Group2"){
     echo 'This is description '.$val['description'];
   }
}

1 Comment

Here you need not to seperate them like key and vlaue but makesure even as value for searching
0

You'll have to iterate over the main array and scan it for that title.

Assuming your main array is called $groups :

$title = 'Group2';
foreach($groups as $key => $group){
  if ($group['title'] == $title){
    $groupDescription = $group['description'];
    // if you need to reference this group again, save it's key.
    $groupKey = $key;
  }
}

You can insert a break command after you have found the group you are looking for to terminate the loop so that it will not continue to scan the array after you have found the one you are looking for.

2 Comments

Do I need to add the break to yours too? :]
@nic - it all depends what the OP wants to do with the groups. I've added a note about the break command... But please don't edit other users code blocks - rather leave a comment (like you did on mine) and let the user decide whether or not they want to add it to their answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.