Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of element in an array by the value

Tags:

php

I have this array in PHP:

array(     [0] => array( 'username' => 'user1' )     [1] => array( 'username' => 'user2' ) ) 

If I have the 'username' string how can I get the index value as a number?

Example, if I have 'user1' how can I get 0?

like image 545
roflwaffle Avatar asked May 13 '09 00:05

roflwaffle


People also ask

How do you find the index of an element in an array in JS?

The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.

Can you use indexOf in an array?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you find the index of an element in an array in Python?

The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.

How do you find the index of an array element in C++?

Using std::find_if algorithm For instance, find the index of the first 2-digit number in the array. The recommended approach is to use the std::find_if algorithm, which accepts a predicate to handle such cases. That's all about finding the index of an element in an array in C++.


1 Answers

Take a look at array_search.

From the PHP help file:

<?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; ?> 
like image 102
Dan Walker Avatar answered Sep 29 '22 11:09

Dan Walker