- [ Solved – 10 Answers ] PHP – Insert new item in array on any position in PHP
- It only requires one function call to array_splice:
- Here is the solution for insert arrays:
- A function that can insert at both integer and string positions:
- Integer usage:
- String Usage:
- We can use this:
- Here is the another Solution: –
- PHP Code:
- Sample Output:
- Hint for adding an element at the beginning of an array:
- then:
- but:
- First we invoke unshift passing a single argument, then multiple arguments, displaying the results using console.log:
- Here is simple function for insert new element after a specific key, while preserving integer keys:
- Normally, with scalar values:
- To insert a single array element into our array don’t forget to wrap the array in an array (as it was a scalar value!):
- Как вставить новый элемент в массив в любую позицию на PHP
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
[ Solved – 10 Answers ] PHP – Insert new item in array on any position in PHP
How can we insert a new item into an array on any position, say for example in the middle of array?
How can we insert a new item into an array on any position?
It only requires one function call to array_splice:
[pastacode lang=”php” manual=”%24original%20%3D%20array(%20%E2%80%98w’%2C%20%E2%80%98i’%2C%20%E2%80%98k’%2C%20%E2%80%98e’%2C%20%E2%80%98t’%20)%3B%0A%24inserted%20%3D%20array(%20’x’%20)%3B%20%2F%2F%20Not%20necessarily%20an%20array%0A%0Aarray_splice(%20%24original%2C%203%2C%200%2C%20%24inserted%20)%3B%20%2F%2F%20splice%20in%20at%20position%203%0A%2F%2F%20%24original%20is%20now%20w%20i%20k%20x%20e%20t%0A” message=”Php Code” highlight=”” provider=”manual”/]Here is the solution for insert arrays:
[pastacode lang=”php” manual=”function%20array_insert(%26%24array%2C%20%24value%2C%20%24index)%0A%7B%0A%20%20%20%20return%20%24array%20%3D%20array_merge(array_splice(%24array%2C%20max(0%2C%20%24index%20-%201))%2C%20array(%24value)%2C%20%24array)%3B%0A%7D%0A” message=”Php Code” highlight=”” provider=”manual”/]A function that can insert at both integer and string positions:
[pastacode lang=”php” manual=”%2F**%0A%20*%20%40param%20array%20%20%20%20%20%20%24array%0A%20*%20%40param%20int%7Cstring%20%24position%0A%20*%20%40param%20mixed%20%20%20%20%20%20%24insert%0A%20*%2F%0Afunction%20array_insert(%26%24array%2C%20%24position%2C%20%24insert)%0A%7B%0A%20%20%20%20if%20(is_int(%24position))%20%7B%0A%20%20%20%20%20%20%20%20array_splice(%24array%2C%20%24position%2C%200%2C%20%24insert)%3B%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%24pos%20%20%20%3D%20array_search(%24position%2C%20array_keys(%24array))%3B%0A%20%20%20%20%20%20%20%20%24array%20%3D%20array_merge(%0A%20%20%20%20%20%20%20%20%20%20%20%20array_slice(%24array%2C%200%2C%20%24pos)%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%24insert%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20array_slice(%24array%2C%20%24pos)%0A%20%20%20%20%20%20%20%20)%3B%0A%20%20%20%20%7D%0A%7D%0A” message=”Php Code” highlight=”” provider=”manual”/]Integer usage:
[pastacode lang=”php” manual=”%24arr%20%3D%20%5B%22one%22%2C%20%22two%22%2C%20%22three%22%5D%3B%0Aarray_insert(%0A%20%20%20%20%24arr%2C%0A%20%20%20%201%2C%0A%20%20%20%20%22one-half%22%0A)%3B%0A%2F%2F%20-%3E%0Aarray%20(%0A%20%200%20%3D%3E%20’one’%2C%0A%20%201%20%3D%3E%20’one-half’%2C%0A%20%202%20%3D%3E%20’two’%2C%0A%20%203%20%3D%3E%20’three’%2C%0A)%0A” message=”Php Code” highlight=”” provider=”manual”/]String Usage:
[pastacode lang=”php” manual=”%24arr%20%3D%20%5B%0A%20%20%20%20%22name%22%20%20%3D%3E%20%5B%0A%20%20%20%20%20%20%20%20%22type%22%20%20%20%20%20%20%3D%3E%20%22string%22%2C%0A%20%20%20%20%20%20%20%20%22maxlength%22%20%3D%3E%20%2240%22%2C%0A%20%20%20%20%5D%2C%0A%20%20%20%20%22email%22%20%3D%3E%20%5B%0A%20%20%20%20%20%20%20%20%22type%22%20%20%20%20%20%20%3D%3E%20%22email%22%2C%0A%20%20%20%20%20%20%20%20%22maxlength%22%20%3D%3E%20%22160%22%2C%0A%20%20%20%20%5D%2C%0A%5D%3B%0A%0Aarray_insert(%0A%20%20%20%20%24arr%2C%0A%20%20%20%20%22email%22%2C%0A%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%22phone%22%20%3D%3E%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20%22type%22%20%20%20%3D%3E%20%22string%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22format%22%20%3D%3E%20%22phone%22%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%5D%0A)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/] [pastacode lang=”php” manual=”%2F%2F%20-%3E%0Aarray%20(%0A%20%20’name’%20%3D%3E%0A%20%20array%20(%0A%20%20%20%20’type’%20%3D%3E%20’string’%2C%0A%20%20%20%20’maxlength’%20%3D%3E%20’40’%2C%0A%20%20)%2C%0A%20%20’phone’%20%3D%3E%0A%20%20array%20(%0A%20%20%20%20’type’%20%3D%3E%20’string’%2C%0A%20%20%20%20’format’%20%3D%3E%20’phone’%2C%0A%20%20)%2C%0A%20%20’email’%20%3D%3E%0A%20%20array%20(%0A%20%20%20%20’type’%20%3D%3E%20’email’%2C%0A%20%20%20%20’maxlength’%20%3D%3E%20’160’%2C%0A%20%20)%2C%0A)%0A” message=”Php Code” highlight=”” provider=”manual”/]We can use this:
[pastacode lang=”php” manual=”foreach%20(%24array%20as%20%24key%20%3D%3E%20%24value)%20%0A%7B%0A%20%20%20%20if(%24key%3D%3D1)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%24new_array%5B%5D%3D%24other_array%3B%0A%20%20%20%20%7D%20%20%20%0A%20%20%20%20%24new_array%5B%5D%3D%24value%3B%20%20%20%20%0A%7D%0A” message=”Php Code” highlight=”” provider=”manual”/]Here is the another Solution: –
PHP Code:
[pastacode lang=”php” manual=”%3C%3Fphp%20%20%0A%24original%20%3D%20array(%20’1’%2C’2’%2C’3’%2C’4’%2C’5’%20)%3B%20%20%0Aecho%20’Original%20array%20%3A%20′.%22%5Cn%22%3B%20%20%0Aforeach%20(%24original%20as%20%24x)%20%20%20%0A%7Becho%20%22%24x%20%22%3B%7D%20%20%0A%24inserted%20%3D%20’%24’%3B%20%20%0Aarray_splice(%20%24original%2C%203%2C%200%2C%20%24inserted%20)%3B%20%20%20%0Aecho%20%22%20%5Cn%20After%20inserting%20’%24’%20the%20array%20is%20%3A%20%22.%22%5Cn%22%3B%20%20%0Aforeach%20(%24original%20as%20%24x)%20%20%20%0A%7Becho%20%22%24x%20%22%3B%7D%20%20%0Aecho%20%22%5Cn%22%20%20%0A%3F%3E%20%0A” message=”Php Code” highlight=”” provider=”manual”/]Sample Output:
Original array :
1 2 3 4 5
After inserting ‘$’ the array is :
1 2 3 $ 4 5
- splice method can be used for adding and/or removing elements from an array.
- The first argument specifies the location at which to begin adding or removing elements.
- The second argument specifies the number of elements to delete.
- When using splice to add elements to an array, the second argument would be zero.
- The third and subsequent arguments are elements to be added to the array.
Hint for adding an element at the beginning of an array:
[pastacode lang=”php” manual=”%24a%20%3D%20array(‘first’%2C%20’second’)%3B%0A%24a%5B-1%5D%20%3D%20’i%20am%20the%20new%20first%20element’%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]then:
[pastacode lang=”php” manual=”foreach(%24a%20as%20%24aelem)%0A%20%20%20%20echo%20%24a%20.%20’%20’%3B%0A%2F%2Freturns%20first%2C%20second%2C%20i%20am…%0A%0A” message=”Php Code” highlight=”” provider=”manual”/]but:
[pastacode lang=”php” manual=”for%20(%24i%20%3D%20-1%3B%20%24i%20%3C%20count(%24a)-1%3B%20%24i%2B%2B)%0A%20%20%20%20%20echo%20%24a%20.%20’%20’%3B%0A%2F%2Freturns%20i%20am%20as%201st%20element%0A” message=”Php Code” highlight=”” provider=”manual”/]- Add Elements to the Beginning of an Array:
- unshift method is used to add elements to the beginning of an array.
- It accepts multiple arguments, adjusts the indexes of existing elements, and returns the new length of the array.
- The unshift method modifies the array on which it is invoked.
First we invoke unshift passing a single argument, then multiple arguments, displaying the results using console.log:
[pastacode lang=”php” manual=”var%20ar%20%3D%20%5B’one’%2C%20’two’%2C%20’three’%5D%3B%0A%2F%2F%20add%20single%20element%0Aar.unshift(‘zero’)%3B%0Aconsole.log(%20ar%20)%3B%20%2F%2F%20%5B%22zero%22%2C%20%22one%22%2C%20%22two%22%2C%20%22three%22%5D%0A%0A%2F%2F%20add%20multiple%20elements%0Aar.unshift(0%2C%201%2C%202%2C%203)%3B%0Aconsole.log(%20ar%20)%3B%20%2F%2F%20%5B0%2C%201%2C%202%2C%203%2C%20%22zero%22%2C%20%22one%22%2C%20%22two%22%2C%20%22three%22%5D%0A” message=”Php Code” highlight=”” provider=”manual”/]Here is simple function for insert new element after a specific key, while preserving integer keys:
[pastacode lang=”php” manual=”private%20function%20arrayInsertAfterKey(%24array%2C%20%24afterKey%2C%20%24key%2C%20%24value)%7B%0A%20%20%20%20%24pos%20%20%20%3D%20array_search(%24afterKey%2C%20array_keys(%24array))%3B%0A%0A%20%20%20%20return%20array_merge(%0A%20%20%20%20%20%20%20%20array_slice(%24array%2C%200%2C%20%24pos%2C%20%24preserve_keys%20%3D%20true)%2C%0A%20%20%20%20%20%20%20%20array(%24key%3D%3E%24value)%2C%0A%20%20%20%20%20%20%20%20array_slice(%24array%2C%20%24pos%2C%20%24preserve_keys%20%3D%20true)%0A%20%20%20%20)%3B%0A%7D%20%0A” message=”Php Code” highlight=”” provider=”manual”/]Normally, with scalar values:
[pastacode lang=”php” manual=”%24elements%20%3D%20array(‘foo’%2C%20…)%3B%0Aarray_splice(%24array%2C%20%24position%2C%20%24length%2C%20%24elements)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]To insert a single array element into our array don’t forget to wrap the array in an array (as it was a scalar value!):
[pastacode lang=”php” manual=”%24element%20%3D%20array(‘key1’%3D%3E’value1’)%3B%0A%24elements%20%3D%20array(%24element)%3B%0Aarray_splice(%24array%2C%20%24position%2C%20%24length%2C%20%24elements)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]Как вставить новый элемент в массив в любую позицию на PHP
Как я могу вставить новый элемент в массив в любую позицию, например, в середину массива?
Ответ 1
Вы можете сделать это простым интуитивным способом. Для этого требуется только один вызов функции array_splice :
$original = array( ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ );
$inserted = array( ‘x’ ); // не обязательно массив, см. руководство
array_splice( $original, 3, 0, $inserted ); // вставка в позициию+
3
// $original теперь a b c x d e
Если операция замена и для одного элемента, то нет необходимости помещать его в array(), если только этот элемент не является самим массивом, объектом или NULL.
Ответ 2
Ответ 3
Не существует встроенной функции в PHP, которая могла бы делать именно то, что вы просили.
Я написал 2 метода, которые, как мне кажется, подходят для данного вопроса:
function insertBefore($input, $index, $element)
if (!array_key_exists($index, $input))
throw new Exception(«Index not found»);
>
$tmpArray = array();
$originalIndex = 0;
foreach ($input as $key => $value)
if ($key === $index)
$tmpArray[] = $element;
break;
>
$tmpArray[$key] = $value;
$originalIndex++;
>
array_splice($input, 0, $originalIndex, $tmpArray);
return $input;
>
function insertAfter($input, $index, $element)
if (!array_key_exists($index, $input))
throw new Exception(«Index not found»);
>
$tmpArray = array();
$originalIndex = 0;
foreach ($input as $key => $value)
$tmpArray[$key] = $value;
$originalIndex++;
if ($key === $index)
$tmpArray[] = $element;
break;
>
>
array_splice($input, 0, $originalIndex, $tmpArray);
return $input;
>
Хотя это быстрее , и, вероятно, с большей эффективностью можно использовать для экономии памяти, это действительно подходит только там, где нет необходимости поддерживать ключи массива. Если вам действительно нужно поддерживать ключи, более подходящим будет следующее:
function insertBefore($input, $index, $newKey, $element)
if (!array_key_exists($index, $input))
throw new Exception(«Index not found»);
>
$tmpArray = array();
foreach ($input as $key => $value)
if ($key === $index)
$tmpArray[$newKey] = $element;
>
$tmpArray[$key] = $value;
>
return $input;
>
function insertAfter($input, $index, $newKey, $element)
if (!array_key_exists($index, $input))
throw new Exception(«Index not found»);
>
$tmpArray = array();
foreach ($input as $key => $value)
$tmpArray[$key] = $value;
if ($key === $index)
$tmpArray[$newKey] = $element;
>
>
return $tmpArray;
>
Ответ 4
Вот что у меня сработало для ассоциативного массива:
/*
* Вставляет новый ключ/значение после ключа в массиве.
*
* @param $key
* Ключ, после которого нужно вставить значение.
* @param $array
* Массив для вставки.
* @param $new_key
* Ключ для вставки.
* @param $new_value
* Значение для вставки.
*
* @return
* Новый массив, если ключ существует, FALSE в противном случае.
*
* @see array_insert_before()
*/
function array_insert_after($key, array &$array, $new_key, $new_value)
if (array_key_exists($key, $array))
$new = array();
foreach ($array as $k => $value)
$new[$k] = $value;
if ($k === $key)
$new[$new_key] = $new_value;
>
>
return $new;
>
return FALSE;
>
Ответ 5
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.