php add array key to array

How to add keys to php array?

this code adding the key in to an array. But it also adding the indexed key to same key/value pair..how to avoid this indexed key? output:

9 Answers 9

Just add another key value like this

Don’t use array_push() here it’s not necessary. Just add new key with value.

php add array key to array. Смотреть фото php add array key to array. Смотреть картинку php add array key to array. Картинка про php add array key to array. Фото php add array key to array

Just add the new key.

You can add more elements by this way:

In addition to the others: you can push elements to the array, but there’s no documented way (http://php.net/array_push) to choose your own keys. So array_push uses numeric index by itself.

A possible alternative for associative array is using an (anonymous) object ( stdClass ). In that case you can set properties and it’s a little bit more OOP style of coding.

php add array key to array. Смотреть фото php add array key to array. Смотреть картинку php add array key to array. Картинка про php add array key to array. Фото php add array key to array

Push the new key-value pair into the array like so:

Keys not found within the array will get created.

array_push is basically an operation which treats an array as a stack. Stacks don’t have keys, so using an associative array with array_push does not make sense (since you wouldn’t be able to retrieve the key with array_pop anyway).

If you want to simulate the behaviour of array_push which allows the simultaneous addition of multiple entries you can do the following:

php add array key to array. Смотреть фото php add array key to array. Смотреть картинку php add array key to array. Картинка про php add array key to array. Фото php add array key to array

Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

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.

Источник

How to push both value and key into PHP array

Take a look at this code:

I’m looking for something like this so that:

Is there a function to do this? (because array_push won’t work this way)

php add array key to array. Смотреть фото php add array key to array. Смотреть картинку php add array key to array. Картинка про php add array key to array. Фото php add array key to array

20 Answers 20

Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.

php add array key to array. Смотреть фото php add array key to array. Смотреть картинку php add array key to array. Картинка про php add array key to array. Фото php add array key to array

Pushing a value into an array automatically creates a numeric key for it.

When adding a key-value pair to an array, you already have the key, you don’t need one to be created for you. Pushing a key into an array doesn’t make sense. You can only set the value of the specific key in the array.

You can use the union operator ( + ) to combine arrays and keep the keys of the added array. For example:

There’s more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.

I would like to add my answer to the table and here it is :

hope that this will help somebody

Exactly what Pekka said.

Alternatively, you can probably use array_merge like this if you wanted:

But I’d prefer Pekka’s method probably as it is much simpler.

I wonder why the simplest method hasn’t been posted yet:

php add array key to array. Смотреть фото php add array key to array. Смотреть картинку php add array key to array. Картинка про php add array key to array. Фото php add array key to array

I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.

I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.

Pretty easy & simple really

So like the other posts explain. In php there is no need to «PUSH» an array when you are using

AND. There is no need to define the array first either.

I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP. hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!

Источник

array_push

(PHP 4, PHP 5, PHP 7, PHP 8)

array_push — Добавляет один или несколько элементов в конец массива

Описание

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

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

Возвращает новое количество элементов в массиве.

Список изменений

ВерсияОписание
7.3.0Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра.

Примеры

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

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

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

User Contributed Notes 35 notes

If you’re going to use array_push() to insert a «$key» => «$value» pair into an array, it can be done using the following:

It is not necessary to use array_push.

Hope this helps someone.

Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do.

. but this is actually not true. Unlike array_push and even.

. Rodrigo’s suggestion is NOT guaranteed to append the new element to the END of the array. For instance.

$data[‘one’] = 1;
$data[‘two’] = 2;
$data[‘three’] = 3;
$data[‘four’] = 4;

. might very well result in an array that looks like this.

[ «four» => 4, «one» => 1, «three» => 3, «two» => 2 ]

I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won’t matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.

If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead.

$data[‘one’] = 1;
$data += [ «two» => 2 ];
$data += [ «three» => 3 ];
$data += [ «four» => 4 ];

You can also, of course, append more than one element at once.

$data[‘one’] = 1;
$data += [ «two» => 2, «three» => 3 ];
$data += [ «four» => 4 ];

. which will result in an array that looks like this.

[ «element1» => 1, «element2» => 2, «element3» => 3, «element4» => 4 ]

This is how I add all the elements from one array to another:

If you’re adding multiple values to an array in a loop, it’s faster to use array_push than repeated [] = statements that I see all the time:

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

Adding 100k elements to array with array_push

Adding 100k elements to array with [] 10 per iteration

Adding 100k elements to array with array_push 10 per iteration

?>
The above will output this:
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => a
[1] => b
[2] => c
)
)

There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output «d,e,f», not «a,b,c».

Need a real one-liner for adding an element onto a new array name?

Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does. There’s another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn’t check if a variable is an array first as array_push does. If array_push finds that a variable isn’t an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.

If you want to preserve the keys in the array, use the following:

elegant php array combinations algorithm

A common operation when pushing a value onto a stack is to address the value at the top of the stack.

This can be done easily using the ‘end’ function:

A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

Add elements to an array before or after a specific index or key:

Источник

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’);

Источник

Функции для работы с массивами

Содержание

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.

Источник

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

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