php array get array index

How can I get the current element number when I’m traversing a array?

I know about count(), but I was hoping there’s a built-in function for getting the current field index too, without having to add a extra counter variable.

7 Answers 7

You should use the key() function.

should return the current key.

If you need the position of the current key:

PHP arrays are both integer-indexed and string-indexed. You can even mix them:

Another solution for you is to coerce the array to an integer-indexed list of values.

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka ‘s answer, but solving the 2x looping of the array.

What you can do is create an array with all your keys, in the order they exist, and then loop through that.

PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

an array does not contain index when elements are associative. An array in php can contain mixed values like this:

What are you trying to achieve since you need the index value in an associative array?

There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item’s key first:

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

Not the answer you’re looking for? Browse other questions tagged php arrays field or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Get the index of a certain value in an array in PHP

I want to get the index for a given value (i.e. 1 for string2 and 2 for string3 )

All I want is the position of the strings in the array

How to achieve this?

12 Answers 12

array_search is the way to do it.

You could loop over the array manually and find the index but why do it when there’s a function for that. This function always returns a key and it will work well with associative and normal arrays.

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

If you’re only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

If you want all (or a lot of them), a loop will prob do you better:

Other folks have suggested array_search() which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values() :

You said in your question that array_search() was no use. Can you explain why? What did you try and how did it not meet your needs?

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

// or considering your array structure:

The problem is that you don’t have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

Could you be a little more specific?

works fine for me. Are you trying to accomplish something more complex?

This code should do the same as your new routine, working with the correct multi-dimensional array..

Try the array_keys PHP function.

array_search should work fine, just tested this and it returns the keys as expected:

Or for the index, you could use

You’ll have to create a function for this. I don’t think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

Not the answer you’re looking for? Browse other questions tagged php arrays or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

array

(PHP 4, PHP 5, PHP 7, PHP 8)

array — Create an array

Description

Creates an array. Read the section on the array type for more information on what an array is.

Parameters

Syntax «index => values», separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

Return Values

Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.

Examples

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example #1 array() example

Example #2 Automatic index with array()

The above example will output:

Note that index ‘3’ is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

This example creates a 1-based array.

Example #3 1-based index with array()

The above example will output:

As in Perl, you can access a value from the array inside double quotes. However, with PHP you’ll need to enclose your array between curly braces.

Example #4 Accessing an array inside double quotes

Notes

array() is a language construct used to represent literal arrays, and not a regular function.

See Also

User Contributed Notes 38 notes

As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.

So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.

Here’s a further example:

$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);

$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);

$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);

Источник

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_search — Осуществляет поиск данного значения в массиве и возвращает ключ первого найденного элемента в случае успешного выполнения

Описание

Список параметров

Если needle является строкой, сравнение происходит с учётом регистра.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_search()

Смотрите также

User Contributed Notes 44 notes

in (PHP 5 >= 5.5.0) you don’t have to write your own function to search through a multi dimensional array

$userdb=Array
(
(0) => Array
(
(uid) => ‘100’,
(name) => ‘Sandra Shush’,
(url) => ‘urlof100’
),

(1) => Array
(
(uid) => ‘5465’,
(name) => ‘Stefanie Mcmohn’,
(pic_square) => ‘urlof100’
),

(2) => Array
(
(uid) => ‘40489’,
(name) => ‘Michael’,
(pic_square) => ‘urlof40489’
)
);

simply u can use this

$key = array_search(40489, array_column($userdb, ‘uid’));

About searcing in multi-dimentional arrays; two notes on «xfoxawy at gmail dot com»;

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you’d expect.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn’t call array_column() for each element it searches. For a better performance, you could do;

It’s what the document stated «may also return a non-Boolean value which evaluates to FALSE.»

the recursive function by tony have a small bug. it failes when a key is 0

here is the corrected version of this helpful function:

If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don’t know what I’m talking about, here’s an example:

hallo every body This function matches two arrays like
search an array like another or not array_match which can match

for searching case insensitive better this:

About searcing in multi-dimentional arrays;
note on «xfoxawy at gmail dot com» and turabgarip at gmail dot com;

$xx = array_column($array, ‘NAME’, ‘ID’);
will produce an array like :
$xx = [
[ID_val] => NAME_val
[ID_val] => NAME_val
]

$yy = array_search(‘tesxt’, array_column($array, ‘NAME’, ‘ID’));
will output expected ID;

To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.

The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()

Be careful when search for indexes from array_keys() if you have a mixed associative array it will return both strings and integers resulting in comparison errors

/* The above prints this, as you can see we have mixed keys
array(3) <
[0]=>
int(0)
[1]=>
string(3) «car»
[2]=>
int(1)
>
*/

hey i have a easy multidimensional array search function

Despite PHP’s amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

But again, with the above solution, PHP again falls short on how to dynamically access a specific element’s value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

I needed a way to return the value of a single specific key, thus:

Better solution of multidimensional searching.

FYI, remember that strict mode is something that might save you hours.

one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings. (or even a string that looks like a number)

The problem is that unless you specify «strict» the match is done using == and in that case any string will match a numeric value of zero which is not what you want.

also, php can lookup an index pretty darn fast. for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

//very fast lookup, this beats any other kind of search

I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively, not by a simple internal pointer check as with class objects. The === can be slow for massive arrays and also crash if they contain circular references.

This function performs reference sniffing in order to return the key for an element that is exactly a reference of needle.

A simple recursive array_search function :

A variation of previous searches that returns an array of keys that match the given value:

I needed a function, that returns a value by specifying a keymap to the searched value in a multidimensional array and came up with this.

My function get_key_in_array() needed some improvement:

An implementation of a search function that uses a callback, to allow searching for objects of arbitrary complexity:

For instance, if you have an array of objects with an id property, you could search for the object with a specific id like this:

For a more complex example, this function takes an array of key/value pairs and returns the key for the first item in the array that has all those properties with the same values.

The final step is a function that returns the item, rather than its key, or null if no match found:

Источник

PHP: Can I get the index in an array_map function?

I’m using a map in php like so:

Is it possible to get the index of the value in the function?

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

6 Answers 6

Sure you can, with the help of array_keys():

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

php array get array index. Смотреть фото php array get array index. Смотреть картинку php array get array index. Картинка про php array get array index. Фото php array get array index

When mapping an anonymous function over an anonymous array, there is no way to access the keys:

array_reduce doesn’t get access to the keys either. array_walk can access keys, but the array is passed by reference, which requires a layer of indirection.

Some solutions are:

Array of pairs

This is bad, since we’re changing the original array. Plus the boilerplate «array()» calls increase linearly with the length of the array:

Temporary variable

We’re acting on the original array, and the boilerplate is constant, but we can easily clobber an existing variable:

One-shot function

We can use function scope to prevent clobbering existing names, but have to add an extra layer of «use»:

Multi-argument one-shot function

We define the function we’re mapping in the original scope to prevent the «use» boilerplate):

New function

The interesting thing to note is that our last one-shot function has a nice, generic signature and looks a lot like array_map. We might want to give this a name and re-use it:

Our application code then becomes:

Indirect Array Walk

When writing the above I’d ignored array_walk since it requires its argument to be passed by reference; however, I’ve since realised that it’s easy to work around this using call_user_func. I think this is the best version so far:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *