php array index by value
array_values
(PHP 4, PHP 5, PHP 7, PHP 8)
array_values — Выбирает все значения массива
Описание
Список параметров
Возвращаемые значения
Возвращает индексированный массив значений.
Примеры
Пример #1 Пример использования array_values()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 25 notes
Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.
Doing this will cause PHP exceeds the momory limits:
Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).
echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>
If you are looking for a way to count the total number of times a specific value appears in array, use this function:
I needed a function that recursively went into each level of the array to order (only the indexed) arrays. and NOT flatten the whole thing.
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:
/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
same array_flatten function, compressed and preserving keys.
/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/
Non-recursive simplest array_flatten.
A modification of wellandpower at hotmail.com’s function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.
Please note that ‘wellandpower at hotmail.com’s recursive merge doesn’t work. Here’s the fixed version:
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.
I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.
In order to do this, you will want this function:
function array_values_recursive($array) <
$temp = array();
Hopefully this will assist.
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus «preserving keys» may have different interpretations. Ivan’s function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.
/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/
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.
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?
// 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:
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_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:
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’);
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.