php get keys from array

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.

Источник

How to get all keys from a array that start with a certain string?

I have an array that looks like this:

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

9 Answers 9

Procedural approach using objects:

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

This is how I would do it, though I can’t give you a more efficient advice before understanding what you want to do with the values you get.

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

Simply I used array_filter function to achieve the solution as like follows

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

From PHP 5.3 you can use the preg_filter function: here

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

Modification to erisco‘s Functional approach,

this worked for me.

In addition to @Suresh Velusamy’s answer above (which needs at least PHP 5.6.0) you can use the following if you are on a prior version of PHP:

From PHP5.6, the array keys can be the sole subject of the filtration by using the ARRAY_FILTER_USE_KEY constant/flag.

From PHP8, str_starts_with() can take the place of strpos(. ) === 0

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

Not the answer you’re looking for? Browse other questions tagged php arrays array-filter 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.

Источник

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’ :

Источник

How to get array key from corresponding array value?

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

5 Answers 5

You could use array_search() to find the first matching key.

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

You can use the array_keys function for that.

Example:

This will get the key from the array for value blue

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

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

If you do this often, create a reverse array/hash that maps values back to keys. Keep in mind multiple keys may map to a single value.

Your array values can be duplicates so it wont give you exact keys. However the way i think is fine is like iterate over and read the keys

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.

Источник

Print the keys of an array

I could not figure out how to pass a variable number of variables into a function. I thought passing in an array and using the array keys for the variables names could replace the need to pass extra variables into the function, and it worked (I’m sure there is a better way to accomplish this, suggestions welcome). However, I can’t seem to get the keys out of the array inside the function.

Inside the function:

The code inside the function retuns a warning: Invalid argument supplied for foreach(). How can I pull the keys out of the array?

8 Answers 8

You can use PHP’s array_keys function to grab the keys, like so:

Or, you can run through the array using a special foreach which allows you to separate the key and value for every element, like so:

Also, make sure that you are using a «string» (with quotes) or integer (like 1337 ) as your key, like so:

OR if you want to get fancier:

Your code should look like:

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

Passing an associative array to a function is a reasonable way to pass in a variable number of parameters.

Alternatively you could pass in an instance of stdClass (casting the argument to an object). But an array does the job.

I assume your array keys aren’t constants, in which case they should be quoted strings:

The array_keys function will return an array of all the array keys.

I’m sure there is a better way to accomplish this, suggestions welcome

Because you asked for alternate suggestions, here’s one. You can use varargs to pass a variable number of arguments to a function. Here’s an example:

This doesn’t offer you «named» arguments, but it does allow you variable numbers of arguments (like you claim you’re trying to do in your question).

Here are some relevant documentation pages:

However, that’s not to say that your array-based approach is a bad one. In some ways it provides batter readability since you’re explicitly mapping keys to values; maintainers reading your code will be better-able to understand what’s being passed to the function. I’m just giving you some options.

Источник

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

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