0

I have a PHP array that prints the following information:

Array ( 
    [0] => 23 
    [1] => 34 
    [2] => 35 
    [3] => 36 
    [4] => 37 
    [5] => 38 
    ..<snip>..
)

I have the value and would like to cross reference it with the array to return a key. For instance, if I have a variable $value = 34 I would want to run a PHP function to return the key, which in this case is 1.

To be more specific, the array is stored in variable $pages and the value is stored in variable $nextID. I tried using array_search with no luck:

How do I go about this?

2
  • It's just key() Commented May 7, 2013 at 21:38
  • No, key returns the key the current element (from the array pointer) in the array. array_search() should return the key for an element, if it's in the array. What is it returning for you? Commented May 7, 2013 at 21:40

2 Answers 2

2

array_search is exactly what you're looking for. I'm not sure how you had problems with it.

$arr = [
    5,
    10,
    15,
    20
];

$value = 15;

echo array_search($value, $arr); // 2
Sign up to request clarification or add additional context in comments.

1 Comment

there's also array_flip which will swap keys<-->values in the array. php.net/manual/en/function.array-flip.php Beware: keys with the same values will be overwritten by the last key/value pair!
0

You could use foreach() like that:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);

function mySearch($array, $search){
    foreach($array as $key => $value){
        if($value == $search){
            return $key;
        }
    }
}

echo mySearch($arr, 3);
?>

1 Comment

for each is generally slower than array_search gist.github.com/Ocramius/1290076

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.