473,666 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

insert an element in numbered array

Hello,
I need to do the following:

Say I have a multidim array:

$array = array();

$array[0]['name'] = 'Kevin';
$array[0]['age'] = 23;

$array[1]['name'] = 'Julia';
$array[1]['age'] = 31;

$array[2]['name'] = 'Bob';
$array[2]['age'] = 26;

$array[3]['name'] = 'Drew';
$array[3]['age'] = 37;

and I have a seperate array:

$person = array();
$person['name'] = 'Dana';
$person['age'] = 33;

now I want to insert the $person array into the $array in such a way
that it ends up at index 1 and the subsequent elements get pushed up and
renumbered, so $array[1] becomes $array[2] and so on.

Does php have a built-in function that does this?
..soma
Jul 17 '05 #1
4 1710
On Wed, 01 Jun 2005 13:29:41 +0200, somaboy mx wrote:
now I want to insert the $person array into the $array in such a way
that it ends up at index 1 and the subsequent elements get pushed up and
renumbered, so $array[1] becomes $array[2] and so on.


No one built-in function, but you could use array_slice and array_merge:

$p = array( 'name' => 'John', 'age' => 42 );
$insertat = 1;

if ( $insertat <= 0 )
{
$a = array_merge( array( $p ), $a );
}
elseif ( $insertat >= count( $a ) )
{
$a[] = $p;
}
else
{
$a0 = array_slice( $a, 0, $insertat );
$a1 = array_slice( $a, $insertat );
$a = array_merge( $a0, array( $p ), $a1 );
}
--
Firefox Web Browser - Rediscover the web - http://getffox.com/
Thunderbird E-mail and Newsgroups - http://gettbird.com/
Jul 17 '05 #2
On Wed, 01 Jun 2005 13:29:41 +0200, somaboy mx <no****@fakemai l.fk> wrote:
Say I have a multidim array:

$array = array();

$array[0]['name'] = 'Kevin';
$array[0]['age'] = 23; [snip]
and I have a seperate array:

$person = array();
$person['name'] = 'Dana';
$person['age'] = 33;

now I want to insert the $person array into the $array in such a way
that it ends up at index 1 and the subsequent elements get pushed up and
renumbered, so $array[1] becomes $array[2] and so on.

Does php have a built-in function that does this?


Yes, array_splice.

<pre>
<?php
$array = array();

$array[0]['name'] = 'Kevin';
$array[0]['age'] = 23;

$array[1]['name'] = 'Julia';
$array[1]['age'] = 31;

$array[2]['name'] = 'Bob';
$array[2]['age'] = 26;

$array[3]['name'] = 'Drew';
$array[3]['age'] = 37;

$person = array();
$person['name'] = 'Dana';
$person['age'] = 33;

print_r($array) ;
print_r($person );

array_splice($a rray, 1, 0, array($person)) ;

print_r($array) ;
?>
</pre>

--
Andy Hassall / <an**@andyh.co. uk> / <http://www.andyh.co.uk >
<http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool
Jul 17 '05 #3
On Wed, 01 Jun 2005 13:42:15 +0100, Andy Hassall wrote:
Yes, array_splice.


Ah damn, overlooked :)
--
Firefox Web Browser - Rediscover the web - http://getffox.com/
Thunderbird E-mail and Newsgroups - http://gettbird.com/
Jul 17 '05 #4
Andy Hassall wrote:
Yes, array_splice.


Thanks! I was afraid that array_splice would merely replace the element
at the given index but obviously it works.

thanks again
..soma
Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
7379
by: Jack | last post by:
I have a text file of data in a file (add2db.txt) where the entries are already entered on separate lines in the following form: INSERT INTO `reviews` VALUES("", "Tony's", "Lunch", "Great atmosphere. Good food.", " (Harry Houdini - 03/01/2004)"); INSERT INTO `reviews` VALUES("", "Le Chow Place", "Lunch", "yada yada", " (Herbert Hoover - 03/03/2004)"); INSERT INTO `reviews` VALUES("", "Golden Dragon", "Lunch", "Exquisite.
19
11283
by: John Keeling | last post by:
Dear all, I tried the test program below. My interest is to examine timing differences between insert vs. append & reverse for a list. My results on my XP Python 2.3.4 are as follows: time_reverse 0.889999389648 time_insert 15.7750005722 Over multiple runs ... the time taken to insert at the head of a list, vs. the time taken to append to a list and then reverse it is typically 16 or 17 times longer. I would have expected the insert...
0
1250
by: Raed Sawalha | last post by:
I have following code that reads a binary file into array of bytes, after I read the file i need to insert a space in fisrt element of array ,how can I achieve this System.IO.FileStream fs = new System.IO.FileStream(fileName,System.IO.FileMode.Open,System.IO.FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); byte sysFile = {0}; while(br.Read() > 0) {
2
4180
by: mirandacascade | last post by:
O/S: Win2K Vsn of Python: 2.4 Example: <a> <b createAnotherWhenCondition="x"> <c>text for c</c> <d>text for d</d> </b>
6
6422
by: flash | last post by:
write a program that manipulates arrays of integers. The main program should call three functions: Insert, Delete, and Search. The Insert function should call a function Sort that sorts the array. Here is a description of the three functions: Insert: Accepts as input the array and the element you want to insert into the array. The function should insert the element at the end of the array and should call the function Sort to sort the...
2
2851
by: Gestorm | last post by:
Suppose we have an array a, the idea is: build another array, int next, for each 0<i<N, next = next position of a in the sorted array, if a is the max, then next is undefined. For example, let the unsorted array is a = {5, 4, 2, 1, 3}; then next would be {undefined, 0, 4, 2, 1} after sorted.
2
2402
by: subramanian100in | last post by:
In ISO/IEC 14882:2003 document, in the section '23.2.1.3 deque modifiers', the following is mentioned: iterator insert(iterator position, const T& x); void insert(iterator position, size_type n, const T& x); template <class InputIterator> void insert(iterator position, InputIterator first, InputIterator last);
2
7336
bugboy
by: bugboy | last post by:
Hi, I have a very long array with sequential numeric keys. What is the best method for inserting an element in the middle thus bumping all following elements along one key.. Like the function array_unshift() but where i can chose where in the key rank to insert the new element. the best i can come with is to loop through each element after the insert and increment their keys by +1 to make room. I'm hoping there is a function for this that...
4
9581
by: ggoubb | last post by:
The purpose of the Insert function is to add a new integer in the Heap assuming that it is not already full. If Heap capacity has been reached, it attempts to double the current capacity. If capacity cannot be doubled, it throws FullHeap. Here is the Heap.h file const int MAXSIZE = 4; // Default maximum heap size class Heap // Smart Heap ADT as an array { private: int* ptr; ...
0
8443
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7385
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5663
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4366
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2769
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1772
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.