1

Is there a way to find if a value exists in a multidimensional array?

$comments_array = array();

$comments_array[] = array(
               "comment" => "comment1", 
               "flag_user_id" => "1",
                user_id => "2", 
               "username" => "Xylon",
               "comment_id" => "3"
         );

$comments_array[] = array(
               "comment" => "comment2", 
               "flag_user_id" => "4", 
               user_id => "2", 
               "username" => "Xylon", 
               "comment_id" => "6"
             );

In the above given array, I want to find if comment2 exits and retrieve it's falg_user_id

VIVEK-MDU
  • 2,483
  • 3
  • 36
  • 63
Xylon
  • 461
  • 4
  • 11
  • 20
  • 1
    you go with a loop for each of them http://stackoverflow.com/questions/6990855/php-check-if-value-and-key-exist-in-multidimensional-array – Netorica Aug 21 '14 at 05:06

3 Answers3

2

In PHP5.5:

$allComments = array_column($comments_array, 'comment');
$key = array_search('comment2', $allComments);
if($key !== false) {
    $flagUserId = $comments_array[$key]['flag_user_id'];
}
Xylon
  • 461
  • 4
  • 11
  • 20
Scopey
  • 6,269
  • 1
  • 22
  • 34
2

Here is an example that I worked out for your question.

foreach ($comments_array as $arr) {
    if (array_key_exists('comment', $arr) && $arr['comment'] == 'comment2') {
        if (array_key_exists('flag_user_id', $arr)) {
            return $arr['flag_user_id'];
        }
    }
    return NULL;
}

array_key_exists() is a PHP method that returns true or false based on if a specified key exists in an array. I simply loop through all sub arrays of your multidimensional array, check if the comments index exists and if it is equal to your specified comment2. If that case is reached, it checks that the flag_user_id index exists and returns it's contents. Otherwise this loop defaults to NULL.

Hope this helps!

BigBerger
  • 1,765
  • 4
  • 23
  • 43
0

try this

$comment_exists = false;

foreach($comments_array as $arr)
{
    if($arr['comment']=='comment2')
    {
          $comment_exists = true;
    }
}

if($comment_exists)
{
     ehco "exists";
}
else
{
     ehco "not exists";
}
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51