php array push key value

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

20 Answers 20

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

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

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

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!

Источник

PHP Add to Array | Push Value to Array PHP – array_push()

Add values or elements to an array in PHP. Here we will learn how to add/push the values/elements to array in PHP with examples.

Here we will learn:-

Here we will take some examples, like add values in array PHP, PHP array push with key, PHP add to an associative array, PHP add to the multidimensional array, array push associative array PHP, PHP array add key-value pair to an existing array.

Add or Insert elements/values to array In PHP

You can use PHP array_push() function for adding one or more elements/values to the end of an array.

Let’s know about the PHP array_push() function, like array_push function definition, syntax, and examples:

PHP array_push() function

The PHP array_push() function is used to add one or more elements to the end of an array.

Syntax

Example 1 – add values in array PHP

In this example, we have one array “array(“PHP”, “laravel”, “codeigniter”)”, it contains value like (“PHP”, “laravel”, “codeigniter”). If we want to add/push one or more values in the array. You can add/push the values into array see below examples:

Here we will add new values like(“WordPress”,”bootstrap”,”HTML”) in existing array using PHP array_push() function:

PHP array push with key

Here we will push the values in array with key without using array function:

PHP add to multidimensional array

If we want to add values/elements in a multi-dimensional array. Here we will take an example for adding the values/elements in a multidimensional array.

If you have a multidimensional array like this:

And you want to add values/elements inside the array elements. You can use the below example for adding the values/elements in the multidimensional array:

How to push array in multidimensional array

Here we will take an example with the multi-dimensional array. In this example, we will push new array into multidimensional-array.

Let’s see the example below:

PHP append one array to another | PHP push array into an array

Now, we will take example of push one array to another array or push array into an array without using array_push() function.

Add one array into another array in PHP:

Conclusion

Array add/push values PHP tutorial. Here you have learned how to add values in array PHP, PHP array push with key, PHP add to an associative array, PHP add to the multidimensional array, array push associative array PHP, PHP array adds key-value pair to an existing array with examples.

Источник

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_push с ассоциативным массивом и индексным ключом?

Я немного устал от php, так как иногда я использую его неделями, а иногда бывает, что вы им не пользуетесь месяцами. В любом случае я пытаюсь передать значения другого массива «массив», в другом массиве упорядоченным образом … Что я хочу сделать, это по сути создать ключ, который позволяет мне организовывать добавочные значения для каждой строки, в частности;

содержимое массива

«;» Он должен быть в состоянии распознать, где вы ломаете линию, я не помню, есть ли какой-нибудь метод, который позволяет мне получить доступ к следующему ключу.

В настоящее время мой код:

Код я верну эту ошибку:

Предупреждение: array_push () Ожидает, что параметр 1 будет массивом, значение NULL будет …

в частности, для array_push кажется, что он не принимает инкрементные ключи или, может быть, я делаю это неправильно.
Может кто-нибудь сказать мне, как решить?

ОБНОВЛЕНИЕ

Как вы уже видели, проблема не проста, и ее довольно сложно объяснить, но я постараюсь быть еще яснее.
Как вы можете видеть выше, вы являетесь структурой массива «массив», но это неупорядоченная структура, которую необходимо упорядочить в дополнительном массиве. Чтобы резюмировать структуру массива «массив» это:

Решение

Вы не можете использовать array_push() в этом случае. Пожалуйста, попробуй:

РЕДАКТИРОВАТЬ

После дополнительного обсуждения у вас есть конкретный формат, где первый элемент является ключом, следующие индексы являются значениями, а когда вы встречаете значение «;», последовательность начинается заново. Итак, когда мы читаем:

Первое значение, «1» — это наш индекс, следующие значения становятся значением этого индекса, и мы прекращаем чтение, когда находим «;». Это будет выглядеть примерно так:

Кажется, мое первоначальное тестирование работает для того, что вы описали. Первый элемент массива становится Индексом, следующие несколько значений становятся развернутыми, пока мы не достигнем точки с запятой ( ; ) значение.

Что я вижу в результате:

В СТОРОНУ

Если бы это был я, я бы поместил все это в массив следующим образом:

Источник

Как вставить значение и ключ в массив PHP

Посмотрите на этот код:

Я ищу что-то вроде этого, чтобы:

Есть ли функция для этого? (потому array_push что не будет работать таким образом)

Нет, array_push() для ассоциативных массивов нет эквивалента, потому что нет способа определить следующий ключ.

Вам придется использовать

Вставка значения в массив автоматически создает для него числовой ключ.

При добавлении пары ключ-значение в массив у вас уже есть ключ, вам не нужно его создавать. Вставка ключа в массив не имеет смысла. Вы можете установить только значение определенного ключа в массиве.

Вы можете использовать оператор union ( + ) для объединения массивов и сохранения ключей добавленного массива. Например:

Я хотел бы добавить свой ответ в таблицу, и вот оно:

надеюсь, что это кому-нибудь поможет

В качестве альтернативы вы можете использовать array_merge следующим образом:

Но я бы предпочел метод Пекки, вероятно, так как он намного проще.

Интересно, почему самый простой метод еще не опубликован:

Это решение, которое может быть полезным для вас

Когда вы бросаете это. Результат как этот

Я просто искал то же самое, и я понял, что, опять же, мое мышление отличается, потому что я старая школа. Я возвращаюсь к BASIC и PERL и иногда забываю, как на самом деле все просто в PHP.

Я просто сделал эту функцию, чтобы взять все настройки из базы данных, где их 3 колонки. setkey, item (key) & value (value) и поместите их в массив, называемый settings, используя тот же ключ / value без использования push, как описано выше.

Довольно легко и просто на самом деле

Источник

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

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