Лун as лун php
(PHP 4, PHP 5, PHP 7, PHP 8)
key — Выбирает ключ из массива
Описание
key() возвращает индекс текущего элемента массива.
Список параметров
Возвращаемые значения
Функция key() просто возвращает ключ того элемента массива, на который в данный момент указывает внутренний указатель массива. Она не сдвигает указатель ни в каком направлении. Если внутренний указатель указывает вне границ массива или массив пуст, key() возвратит null .
Примеры
Пример #1 Пример использования key()
= array(
‘fruit1’ => ‘apple’ ,
‘fruit2’ => ‘orange’ ,
‘fruit3’ => ‘grape’ ,
‘fruit4’ => ‘apple’ ,
‘fruit5’ => ‘apple’ );
// этот цикл выведет все ключи ассоциативного массива,
// значения которых равны «apple»
while ( $fruit_name = current ( $array )) <
if ( $fruit_name == ‘apple’ ) <
echo key ( $array ), «\n» ;
>
next ( $array );
>
?>
Результат выполнения данного примера:
Смотрите также
- current() — Возвращает текущий элемент массива
- next() — Перемещает указатель массива вперёд на один элемент
- foreach
User Contributed Notes 5 notes
Note that using key($array) in a foreach loop may have unexpected results.
When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)
I was incorrectly using:
foreach( $array as $value )
<
$mykey = key ( $array );
>
?>
and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)
CORRECT:
foreach( $array as $key => $value )
<
$mykey = $key ;
>
A noob error , but felt it might help someone else out there .
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this
while ( $fruit_name = current ( $array )) <
echo key ( $array ). ‘
‘ ;
next ( $array );
>
// the way will be break loop when arra(‘2’=>0) because its value is ‘0’, while(0) will terminate the loop
// correct approach
while ( ( $fruit_name = current ( $array )) !== FALSE ) <
echo key ( $array ). ‘
‘ ;
next ( $array );
>
//this will work properly
?>
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.
( $x ); // optional.
arsort ( $x );
$key_of_max = key ( $x ); // returns the index.
?>
(Editor note: Or just use the array_keys function)
Make as simple as possible but not simpler like this one 🙂
$k = array();
for($i = 0; $i
In addition to FatBat’s response, if you’d like to find out the highest key in an array (assoc or not) but don’t want to arsort() it, take a look at this:
= [ ‘3’ => 14 , ‘1’ => 15 , ‘4’ => 92 , ’15’ => 65 ];
$key_of_max = array_search ( max ( $arr ) , $arr );
Источник
array_keys
(PHP 4, PHP 5, PHP 7, PHP 8)
array_keys — Возвращает все или некоторое подмножество ключей массива
Описание
Функция array_keys() возвращает числовые и строковые ключи, содержащиеся в массиве array .
Если указан параметр search_value , функция возвращает ключи у которых значения элементов массива совпадают с этим параметром. В обратном случае, функция возвращает все ключи массива array .
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Возвращает массив со всеми ключами array .
Примеры
Пример #1 Пример использования array_keys()
= array( 0 => 100 , «color» => «red» );
print_r ( array_keys ( $array ));
$array = array( «blue» , «red» , «green» , «blue» , «blue» );
print_r ( array_keys ( $array , «blue» ));
$array = array( «color» => array( «blue» , «red» , «green» ),
«size» => array( «small» , «medium» , «large» ));
print_r ( array_keys ( $array ));
?>
Результат выполнения данного примера:
Смотрите также
- array_values() — Выбирает все значения массива
- array_combine() — Создаёт новый массив, используя один массив в качестве ключей, а другой для его значений
- array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
- array_search() — Осуществляет поиск данного значения в массиве и возвращает ключ первого найденного элемента в случае удачи
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.
for example:
= array( ‘329462291595’ => null , ‘ZZ291595’ => null );
foreach( array_keys ( $importantKeys ) as $key ) <
echo gettype ( $key ). «\n» ;
>
?>
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:
= array( ‘first’ => ‘111’ , ‘second’ => ‘222’ , ‘third’ => ‘333’ );
// get the first key: returns ‘first’
print array_shift ( array_keys ( $array ));
// get the last key: returns ‘third’
print array_pop ( array_keys ( $array ));
// get the first value: returns ‘111’
print array_shift ( array_values ( $array ));
// get the last value: returns ‘333’
print array_pop ( array_values ( $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’) ) );
Valid:
$keys = array_keys( array(‘a’ => ‘apple’) );
echo array_shift( $keys );
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.
function array_keys_recursive ( $myArray , $MAXDEPTH = INF , $depth = 0 , $arrayKeys = array()) <
if( $depth $MAXDEPTH ) <
$depth ++;
$keys = array_keys ( $myArray );
foreach( $keys as $key ) <
if( is_array ( $myArray [ $key ])) <
$arrayKeys [ $key ] = array_keys_recursive ( $myArray [ $key ], $MAXDEPTH , $depth );
>
>
>
return $arrayKeys ;
>
?>
EXAMPLE:
input:
array(
‘Player’ => array(
‘id’ => ‘4’,
‘state’ => ‘active’,
),
‘LevelSimulation’ => array(
‘id’ => ‘1’,
‘simulation_id’ => ‘1’,
‘level_id’ => ‘1’,
‘Level’ => array(
‘id’ => ‘1’,
‘city_id’ => ‘8’,
‘City’ => array(
‘id’ => ‘8’,
‘class’ => ‘home’,
)
)
),
‘User’ => array(
‘id’ => ’48’,
‘gender’ => ‘M’,
‘group’ => ‘user’,
‘username’ => ‘Hello’
)
)
output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)
If an array is empty (but defined), or the $search_value is not found in the array, an empty array is returned (not false, null, or -1). This may seem intuitive, especially given the documentation says an array is returned, but I needed to sanity test to be sure:
= array();
var_dump ( array_keys ( $emptyArray , 99 )); // array (size=0) \ empty
$filledArray = array( 11 , 22 , 33 , 42 );
var_dump ( array_keys ( $filledArray , 99 )); // array (size=0) \ empty
might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates — might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):
= array( «0» => «0» , «1» => «1» , «» => «2» , » » => «3» );
echo ‘how php sees this array: array(«0″=>»0″,»1″=>»1″,»» =>»2″,» «=>»3»)’ , «\n————\n» ;
var_dump ( $r ); print_r ( $r ); var_export ( $r );
echo «\n————\n» , ‘var_dump(«0″,»1″,»»,» «) = ‘ , «\n————\n» ;
var_dump ( «0» , «1» , «» , » » );
?>
OUTPUTS:
It is worth noting that array_keys does not maintain the data-type of the keys when mapping them to a new array. This created an issue with in_array and doing a lookup on characters from a string. NOTE: my lookup $array has a full map of numbers and characters — upper and lower — to do an simple faux encryption with.
= array(
‘e’ => ‘ieio’
, ‘1’ => ‘one’
, ‘2’ => ‘two’
, ‘0’ => ‘zero’
);
var_dump ( $array );
$keys = array_keys ( $array );
var_dump ( $keys );
$string = ‘1e0’ ;
for ( $i = 0 ; $i strlen ( $string ); $i ++) <
if ( in_array ( $string [ $i ], $keys , ‘strict’ )) echo ‘dude ‘ ;
else echo ‘sweet ‘ ;
>
?>
Outputs:
array (size=4)
‘e’ => string ‘ieio’ (length=4)
1 => string ‘one’ (length=3)
2 => string ‘two’ (length=3)
0 => string ‘zero’ (length=4)
array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0
sweet dude sweet
—-
expected to see:
dude dude dude
Источник
Difference between “as $key => $value” and “as $value” in PHP foreach
I have a database call and I’m trying to figure out what the $key => $value does in a foreach loop.
The reason I ask is because both these codes output the same thing, so I’m trying to understand why it’s written this way. Here’s the code:
1)In foreach use $key => $value
this outputs the same as:
2)In foreach use only $value
So my question is, what is the difference between $key => $value or just $value in the foreach loop. The array is multidimensional if that makes a difference, I just want to know why to pass $key to $value in the foreach loop.
8 Answers 8
Well, the $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2. In PHP, associative arrays look like this:
In the PHP code: $featured is the associative array being looped through, and as $key => $value means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key variable to use inside the loop block and the value in the local $value variable. So for our example array above, the foreach loop would reach the first key-value pair, and if you specified as $key => $value , it would store ‘key1’ in the $key variable and ‘value1’ in the $value variable.
Since you don’t use the $key variable inside your loop block, adding it or removing it doesn’t change the output of the loop, but it’s best to include the key-value pair to show that it’s an associative array.
Also note that the as $key => $value designation is arbitrary. You could replace that with as $foo => $bar and it would work fine as long as you changed the variable references inside the loop block to the new variables, $foo and $bar . But making them $key and $value helps to keep track of what they mean.
Источник
A numeric string as array key in PHP
Is it possible to use a numeric string like «123» as a key in a PHP array, without it being converted to an integer?
11 Answers 11
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. «8» will be interpreted as 8, while «08» will be interpreted as «08»).
Addendum
Because of the comments below, I thought it would be fun to point out that the behaviour is similar but not identical to JavaScript object keys.
Yes, it is possible by array-casting an stdClass object:
That gives you (up to PHP version 7.1):
(Update: My original answer showed a more complicated way by using json_decode() and json_encode() which is not necessary.)
Note the comment: It’s unfortunately not possible to reference the value directly: $data[’12’] will result in a notice.
Update:
From PHP 7.2 on it is also possible to use a numeric string as key to reference the value:
If you need to use a numeric key in a php data structure, an object will work. And objects preserve order, so you can iterate.
My workaround is:
The space char (prepend) is a good solution because keep the int conversion:
You’ll see 55 as int.
You can typecast the key to a string but it will eventually be converted to an integer due to PHP’s loose-typing. See for yourself:
From the PHP manual:
A key may be either an integer or a string . If a key is the standard representation of an integer , it will be interpreted as such (i.e. «8» will be interpreted as 8, while «08» will be interpreted as «08»). Floats in key are truncated to integer . The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
I had this problem trying to merge arrays which had both string and integer keys. It was important that the integers would also be handled as string since these were names for input fields (as in shoe sizes etc. )
When I used $data = array_merge($data, $extra); PHP would ‘re-order’ the keys. In an attempt doing the ordering, the integer keys (I tried with 6 — ‘6’ — «6» even (string)»6″ as keys) got renamed from 0 to n . If you think about it, in most cases this would be the desired behaviour.
You can work around this by using $data = $data + $extra; instead. Pretty straight forward, but I didn’t think of it at first ^^.
Strings containing valid integers will be cast to the integer type. E.g. the key «8» will actually be stored under 8. On the other hand «08» will not be cast, as it isn’t a valid decimal integer.
WRONG
I have a casting function which handles sequential to associative array casting,
As workaround, you can encode PHP array into json object, with JSON_FORCE_OBJECT option.
i.e., This example:
I ran into this problem on an array with both ‘0’ and » as keys. It meant that I couldn’t check my array keys with either == or ===.
The workaround is to cast the array keys back to strings before use.
Regarding @david solution, please note that when you try to access the string values in the associative array, the numbers will not work. My guess is that they are casted to integers behind the scenes (when accessing the array) and no value is found. Accessing the values as integers won’t work either. But you can use array_shift() to get the values or iterate the array.
I had this problem while trying to sort an array where I needed the sort key to be a hex sha1. When a resulting sha1 value has no letters, PHP turns the key into an integer. But I needed to sort the array on the relative order of the strings. So I needed to find a way to force the key to be a string without changing the sorting order.
Looking at the ASCII chart (https://en.wikipedia.org/wiki/ASCII) the exclamation point sorts just about the same as space and certainly lower than all numbers and letters.
So I appended an exclamation point at the end of the key string.
Источник