Search an array for a matching string

前端 未结 7 1303
渐次进展
渐次进展 2021-01-23 01:26

I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?

相关标签:
7条回答
  • 2021-01-23 02:00

    Say we have this array:

    <?php
    $array = array(
      1 => 'foo',
      2 => 'bar',
      3 => 'baz',
    );
    ?>
    

    If you want to check if the element 'foo' is in the array, you would do this

    <?php
    if(in_array('foo', $array)) {
      // in array...
    }else{
      // not in array...
    }
    ?>
    

    If you want to get the array index of 'foo', you would do this:

    <?php
    $key = array_search('foo', $array);
    ?>
    

    Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.

    0 讨论(0)
  • Php inArray()

    0 讨论(0)
  • 2021-01-23 02:07

    Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:

    <?php
    
       // $arr is the array to be searched, $needle the string to find.
       // $found is true if the string is found, false otherwise.
    
       $found = false;
       foreach($arr as $key => $value) {
           if($value == $needle) {
               $found = true;
               break;
           }
       }
    
    ?>
    

    I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.

    0 讨论(0)
  • 2021-01-23 02:07

    The array_search function does exactly what you want.

    $index = array_search("string to search for", $array);
    
    0 讨论(0)
  • 2021-01-23 02:11

    Here you go:

    http://www.php.net/manual/en/function.array-search.php

    0 讨论(0)
  • 2021-01-23 02:14

    If you simply want to know if it exists, use in_array(), e.g.:

    $exists = in_array("needle", $haystack);
    

    If you want to know its corresponding key, use array_search(), e.g.:

    $key = array_search("needle", $haystack);
    // will return key for found value, or FALSE if not found
    
    0 讨论(0)
提交回复
热议问题