Hi
I'm looking to search an array for specific keywords, and then return the array key if there is a match.

My array is :

$c[0]="12345";
$c[1]="ABCD,A=0987654,1=\"555666777\",5=DEDEDE,3=\"28FFDE\"";

Which print_r shows as :
print_r($c)."<br>";

Array
(
    [0] => 12345
    [1] => ABCD,A=0987654,1="555666777",5=DEDEDE,3="28FFDE"
)

I'm then exploding $c[1] into a new array:

$l = explode(",",$c[1]);

Which print_r shows as:
print_r($l)."<br>";

Array
(
    [0] => ABCD
    [1] => A=0987654
    [2] => 1="555666777"
    [3] => 5=DEDEDE
    [4] => 3="28FFDE"
)

What I would like to do is search $l for A= and return the key of 1, so I can the reference that key/value later.

A= won't always be at key entry 1, it would be anywhere..

Any ideas ?

I had thought I could use :

$key = array_search('A=', $l);

But that didn't seem to do anything when I echo'd $key;

Any ideas ? Thanks 🙂

    The reason it's not returning anything is because array_search looks for complete matches, rather than a partial match.

    You could try using the array_map() function and pass in the array and a comparison function to check the array's values.

      Thanks for the pointers.
      Got it working with:

      function search_array ( array $array, $term )
      {
          foreach ( $array as $key => $value )
              if ( stripos( $value, $term ) !== false )
                  return $key;
      
      return false;
      }  

        This seems to work OK, but not in PHP 4 !
        I get:
        Parse error: parse error, unexpected T_ARRAY, expecting ')' in

        Any idea how I make this compatible with PHP 4 & 5 ?

          One device I'm planning to run on has PHP4 in built and I can't upgrade it.
          So I need to make sure it will work with both.

          Thanks

            Thanks.. That was me being thick.
            I had removed 'array' and then I got another error.
            I read it as the same error !!

            Now I've re read it I can see it was something different and have resolved that!

            Thanks

              Write a Reply...