php array max key
Find max and min key in associative array
I have associative array like
I want to get lowest and highest key i.e. 1945 and 2012. How can i achieve this? I have already searched over stackoverflow and Hightest value of an associative array is the nearest possibility but it gives out min and max value and I want min and max key.
**I don’t want to use foreach loop **
4 Answers 4
Now you can use min() and max() functions or sort() it get the highest and lowest value easily.
Try this one:
using foreach.
EDIT: This works for simple array. You have 2 level structure, so it would be close to impossible to avoid looping through it.
However, if you have so many entries that even foreach is too slow, probably you should rethink your approach. For example, put this list into database and use SQL to do heavy lifting for you.
How exactly? Setup instance of MySQL or PostgreSQL (I personally prefer Postgres for many reasons), create database, create table with structure like this:
Technically, you should normalize your database and create separate tables for every object (like table for companies, for customers, orders, etc. ), but you can come to this later.
Create indexes on columns you are going to be searching on (like year, company, etc):
Finally, in your PHP script, connect to database and query it for what you wanted, something like this:
Because your input array is «very large» and «consumes [a] lot of time«, that is precisely a justification for using a set of simple language constructs to iterate the dataset in a single pass.
Using multiple array functions may look more concise or clever, but they will be making multiple passes over the data and invariably draw more resources than absolutely necessary.
If you want a more business-agnostic approach, you can seed the default min and max values by shifting the first row off the input array and fetching that subarray’s min and max keys.
Shifted Defaults Code: (Demo)
Neither of these techniques use iterated function calls, so they are virtually assured to perform faster than functional techniques.
Минимальное и максимальное значения массива
Самый простой способ
Разумеется, проще всего получить минимальный и максимальный элементы массива с помощью функций min() и max() :
Однако на форумах часто просят написать скрипт, не использующий эти функции. Чаще всего этого требуют преподаватели учебных учреждений.
Условия задачи
1. Найти наибольший наименьший элементы в одномерном числовом массиве.
2. Определить номер минимального и максимального элементов заданного одномерного массива.
3. Найти минимальное и максимальное значение в ассоциативном массиве.
Общий принцип поиска элементов
Во всех решениях мы будем использовать одну и ту же логику.
Согласно условию, нам необходимо объявить числовой массив произвольной длины. Также объявим 4 переменные, в которые будем помещать найденные значения и их ключи:
Далее перебираем массив в цикле и на каждой итерации проверяем, больше ли текущее значение, чем самое большое, что мы находили до этого.
Пример с циклом foreach:
На данном этапе наш код уже будет работать, но это ещё не всё. Попробуем изменить исходный массив и посмотрим на результат:
Минимальный и максимальный элементы с циклом FOREACH
Решение:
Минимальный и максимальный элементы с циклом WHILE
Решение 1: счётчик + count()
Решение 2: счётчик + isset()
Решение 3: list() + each()
Получился практически аналог foreach. Единственный минус в том, что начиная с PHP 7.2 функция each() объявлена устаревшей.
Решение 4: current() + next()
Наибольший и наименьший элементы с циклом FOR
Решение 1: счётчик + count()
Решение 2: счётчик + isset()
Решение 3: each() + list()
Функция each() возвращает массив с ключом и значением текущего элемента массива, а list() превращает этот массив в 2 разные переменные. После последнего элемента функция each() вернёт false и цикл прекратит работу.
Решение 4: current() + next()
С помощью функции next() смещаем внутренний указатель массива, а функции current() и key() возвращают текущие ключ и значение. Первое и последнее выражение цикла оставляем пустыми.
Максимальное значение в ассоциативном массиве
В ассоциативных массивах отсутствует порядок или системность в названиях ключей, поэтому циклы со счётчиками здесь недоступны.
array_keys
(PHP 4, PHP 5, PHP 7, PHP 8)
array_keys — Возвращает все или некоторое подмножество ключей массива
Описание
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_keys()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 28 notes
It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.
?>
will return on a 64 bits system:
but on a 32 bits system:
I hope it will save someone the huge headache I had 🙂
Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.
Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );
But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:
echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );
However I would expect in time the PHP team will modify the rules of parentheses.
There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.
Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.
NOTE: If the sub element isn’t an array, it will be ignore.
output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)
array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0
—-
expected to see:
dude dude dude
Sorry for my english.
I wrote a function to get keys of arrays recursivelly.
Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
?>
Example usage (pseudo-database code):
= db_query ( ‘SELECT name, value FROM properties’ );
/* This will return an array like so:
/* Now this array looks like:
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com
This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.
An alternative to RQuadling at GMail dot com’s array_remove() function:
The position of an element.
One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».
Hope this helps someone.
# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:
Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)
This function will extract keys from a multidimensional array
Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)
[size] => Array
(
[0] => small
[1] => medium
[2] => large
)
Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)
All the cool notes are gone from the site.
Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.
Simple ways to prefixing arrays;
[1] => Array
(
[product_id] => 2
[product_name] => Bar
)
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.
?>
You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string
A needed a function to find the keys which contain part of a string, not equalling a string.
PHP array_keys
Summary: in this tutorial, you will learn how to use the PHP array_keys() function to get the keys of an array.
Introduction to the PHP array_keys function
The PHP array_keys() function accepts an array and returns all the keys or a subset of the keys of the array.
The array_keys() function returns an array that contains all the keys in the input array.
PHP array_keys() function examples
Let’s take some examples of using the array_keys() function.
1) Using the array_keys() function example
The following example shows how to get all keys of an indexed array:
The following example uses the array_keys() function to get the keys of the array whole value is 20:
The array_keys() function returns the key 1 because key 1 contains the value 20.
2) Using PHP array_keys() function with an associative array example
The following example illustrates how to use the array_keys() function with an associative array:
The following example uses the array_keys() function to get the keys whose values equal 1:
To enable the strict equality comparison (===) when searching, you pass true as the third argument of the array_keys() function like this:
Now, the array_keys() function returns an empty array.
Finding array keys that pass a test
The following function returns the keys of an array, which pass a test specified a callback:
The following example uses the array_keys_by() function above to find the keys that contain the string ‘_post’ :
array
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Создаёт массив
Описание
Создаёт массив. Подробнее о массивах читайте в разделе Массивы.
Список параметров
Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.
Возвращаемые значения
Примеры
Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.
Пример #1 Пример использования array()
Пример #2 Автоматическая индексация с помощью array()
Результат выполнения данного примера:
Этот пример создаёт массив, нумерация которого начинается с 1.
Результат выполнения данного примера:
Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.
Пример #4 Доступ к массиву внутри двойных кавычек
Примечания
Смотрите также
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’);