-1

I have an array $shraniKastomFildove like this:

array(4) { [0]=> string(12) "hashed_token" [1]=> string(17) "registration_time" [2]=> string(12) "noviCustmDev" [3]=> string(2) "no" }

And an array $namesOfCustomFieldsUserWatsToUpdate like this:

array(1) { [0]=> string(12) "noviCustmDev" }

I want to find index of matching element in $shraniKastomFildove. In this case it would be 2, since under index of 2 element with "noviCustmDev" value is stored.

Here is how I tried to get it:

foreach($namesOfCustomFieldsUserWatsToUpdate as $nesto){
    foreach($shraniKastomFildove as $dF){
       if($dF==$nesto){
           var_dump(key($shraniKastomFildove));
       }
     }
 }

But here it dumps number 3. I'm wondering is there a better and more efficient way to get exact value, 2 in this case, or is it due to key() counting indexes for 1 and not from 0?

Ognj3n
  • 759
  • 7
  • 27
  • Possible duplicate of [PHP - Get key name of array value](http://stackoverflow.com/questions/8729410/php-get-key-name-of-array-value) – Epodax Sep 16 '16 at 12:01

1 Answers1

1

You can use the array_search function to search for a value in an array.

This method returns the key for needle if it is found in the array, FALSE otherwise.

So your code will be like this:

foreach($namesOfCustomFieldsUserWatsToUpdate as $nesto){
    $key = array_search($nesto, $shraniKastomFildove);
    var_dump($key);
 }
Daniel Dudas
  • 2,972
  • 3
  • 27
  • 39
  • great, solved it.. i tried already on my own with array_search but from some reason it didn't work as expected – Ognj3n Sep 16 '16 at 12:03