Does value exist in array

in_array() checks if the specified value exits in the array. <<Best for value matching test

  if (in_array("MySearchValue", $MyArray, True))
    //Do something

  if (!in_array("MySearchValue", $MyArray, True))
    //Do something

array_search() searches an array for a given value and returns the key, or False

  if (array_search("MySearchValue", $MyArray, True) !== False)
    //Do something

Note that in_array() is the better choice if you are value matching within an array, because you can test for a True result. array_search() can return a not False result in error conditions

Search a simple array 1 dimensional array

  if (array_search($NewValue, $MyArray) === False)
  {
    //Does not exist
    $MyArray[] = $NewValue;
  }

  //To test if true (returns index if True, so use not false)
  if (array_search($NewValue, $MyArray) !== False)
      
  //For a nested array
  if (array_search($NewValue, $MyArray[$MyKey]['SomeField']) === False)
  {
    //Does not exist
    $MyArray[$MyKey]['SomeField'][] = $NewValue;
  }

#Does a field value exist within a multi dimensional array?

  $MyMultiDimArray = array(    
    0 =>  array(  
      "id" =>  14,
      "name" => "Adam",
    ),  
    1   =>  array(  
        "id" => 2032,
        "name" => "James"
    ), 
    2   =>  array(  
        "id" => 18,
        "name" => "Jane"
    )
  );


  //Simple exists or not
  if (array_search(2032, array_column($MyMultiDimArray, 'id')) !== False)
    echo 'FOUND!';
  else
    echo 'NOT FOUND!';


  //Get key if it exists - looking for match
  $Key = array_search(2032, array_column($MyMultiDimArray, 'id'));
  if ($Key !== False)
  {
    $Name = $MyMultiDimArray[$Key]['name'];
  }


  //Get key if it exists  - create if not exist
  $Key = array_search(2032, array_column($MyMultiDimArray, 'id'));
  if ($Key === False)
  {
    $MyMultiDimArray[]['id'] = 2032;
    $Key = count($MyMultiDimArray) - 1;
  }
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published.