Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP add an item from an array

Tags:

php

Let's say i have this array:

$array = (1,2,4,5);

Now how do i add missing 3 in above array in the correct position index/key-wise?

like image 791
imran haider Avatar asked Nov 11 '10 18:11

imran haider


People also ask

How do you add an element to an array in array?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.

How do you add an item to an array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" ); $arr2 = array ( "GeeksforGeeks" , "Computer science portal" );


1 Answers

Try:

array_splice($array, 2 /*offset*/, 0 /*length*/, 3 /*value*/);

Note that this will reorder the input array's keys from 0 to n-1.

(Edit: The return value is not used in this case.)

like image 101
Matthew Avatar answered Sep 28 '22 02:09

Matthew