php set array keys

array_fill_keys

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

array_fill_keys — Создаёт массив и заполняет его значениями с определёнными ключами

Описание

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

Массив значений, которые будут использованы в качестве ключей. Некорректные ключи массива будут преобразованы в строку ( string ).

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

Возвращает заполненный массив

Примеры

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

Результат выполнения данного примера:

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

User Contributed Notes 8 notes

now string key «1» become an integer value 1, be careful.

Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below

RE: bananasims at hotmail dot com

I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn’t like having an array as the second parameter.

Here’s a slightly modified version than can handle 2 arrays as inputs:

//we want these values to be keys
$arr1 = (0 => «abc», 1 => «def»);
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);

returns:
abc => 452, def =>128

Scratchy’s version still doesn’t work like the definition describes. Here’s one that can take a mixed variable as the second parameter, defaulting to an empty string if it’s not specified. Don’t know if this is exactly how the function works in later versions but it’s at least a lot closer.

This works for either strings or numerics, so if we have

$arr1 = array(0 => ‘abc’, 1 => ‘def’);
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => ‘foo’, 1 => ‘bar’);

array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128

array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0

array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar

array_fill_keys($arr3,’BLAH’)
returns: [foo] => BLAH, [bar] => BLAH

and array_fill_keys($arr1)
returns: [abc] =>, [def] =>

Источник

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 set array keys. Смотреть фото php set array keys. Смотреть картинку php set array keys. Картинка про php set array keys. Фото php set array keys

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.

Источник

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_key_exists

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

array_key_exists — Проверяет, присутствует ли в массиве указанный ключ или индекс

Описание

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

Массив с проверяемыми ключами.

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

array_key_exists() ищет ключи только на первом уровне массива. Внутренние ключи в многомерных массивах найдены не будут.

Примеры

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

Пример #2 array_key_exists() и isset()

Примечания

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

User Contributed Notes 39 notes

If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:

Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms

Note:
The code for this check is very fast, so you shouldn’t warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.

function array_check(. )
<
return (isset(..) || array_key_exists(. ))
>

You’ll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.

= array();
$foo [ ‘bar’ ] = NULL ;

Beware that if the array passed to array_key_exists is NULL, the return value will also be NULL.

This is undocumented behaviour, moreover the documentation (and return typehint) suggest that the array_key_exists function only returns boolean value. But that’s not the case.

Rudi’s multidimensional array_key_exists function was not working for me, so i built one that is.
Enjoy.

The way array_key_exists handles null, float, boolean, and ‘integer-representing string’ keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.

array (
» => 1,
0 => 2,
1 => 3,
4 => 4,
’08’ => 5,
8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
«08» is a key.
«8» is a key.

Well, and you get this warning three times (on the bools and the float, but not on the null):

Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6

I’ve got a new take on the multi key function I would like to share.

Very simple case-insensitive array_key_exists:

bool (in_array(strtolower($needle), array_map(‘strtolower’, array_keys($haystack))))

array_key_exists doesn’t work with objects implementing ArrayAccess interface. It also ignores possible __get() method in such objects, despite the fact it accepts object as a second parameter. It works only with ‘real’ properties.

Here is an example with array_key_exists switching between content-types :

The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:

?>

On Windows, the output is similar to

array_key_exists(): 0.504 [82.895%] seconds
isset(): 0.104 [17.105%] seconds

On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.

Источник

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

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