Purplefish32
Purplefish32

Reputation: 647

What php function can give me the position in the array of a given key

I have an array :

$transport = array('a'=>'foot', 'b'=>'bike', 'c'=>'car', 'd'=>'plane');

What php function can give me the position in the array of a given key ?

ex :

some_function( $transport, 'c')
//expected : 2;

Upvotes: 0

Views: 91

Answers (2)

BoltClock
BoltClock

Reputation: 723448

Search the array's keys for your given key:

$pos = array_search('c', array_keys($transport));

Upvotes: 4

ponzicoder
ponzicoder

Reputation: 25

You could use array_search. Here's a code snippet from http://www.php.net/manual/en/function.array-search.php.

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

Upvotes: 0

Related Questions