Checking if array value exists in a PHP multidimensional array

16,986

Solution 1

What about looping over your array, checking for each item if it's id is the one you're looking for ?

$found = false;
foreach ($your_array as $key => $data) {
    if ($data['id'] == $the_id_youre_lloking_for) {
        // The item has been found => add the new points to the existing ones
        $data['points'] += $the_number_of_points;
        $found = true;
        break; // no need to loop anymore, as we have found the item => exit the loop
    }
}

if ($found === false) {
    // The id you were looking for has not been found, 
    // which means the corresponding item is not already present in your array
    // => Add a new item to the array
}

Solution 2

you can first store the array with index equal to the id. for example :

 $arr =Array ( [0] => Array 
     ( [id] => 1 
       [name] => Jonah 
       [points] => 27 )
    [1] => Array 
     ( [id] => 2 
       [name] => Mark 
       [points] => 34 )
  );
 $new = array();
 foreach($arr as $value){
    $new[$value['id']] = $value; 
 }

//So now you can check the array $new for if the key exists already 
if(array_key_exists(1, $new)){
    $new[1]['points'] = 32;
}
Share:
16,986
user1092780
Author by

user1092780

Updated on June 05, 2022

Comments

  • user1092780
    user1092780 almost 2 years

    I have the following multidimensional array:

    Array ( [0] => Array 
             ( [id] => 1 
               [name] => Jonah 
               [points] => 27 )
            [1] => Array 
             ( [id] => 2 
               [name] => Mark 
               [points] => 34 )
          )
    

    I'm currently using a foreach loop to extract the values from the array:

    foreach ($result as $key => $sub)
    {
        ...
    }
    

    But I was wondering how do I see whether a value within the array already exists.

    So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?

    So after the loop has finished the array will look like this:

    Array ( [0] => Array 
             ( [id] => 1 
               [name] => Jonah 
               [points] => 32 )
            [1] => Array 
             ( [id] => 2 
               [name] => Mark 
               [points] => 34 )
          )