Insert name into an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gprince66
Forum Newbie
Posts: 6
Joined: Tue Feb 14, 2012 11:55 pm

Insert name into an array

Post by gprince66 »

Hi all,

I have an array of several hundred names. I need to insert the name of spouse into the array.

How do I insert Jane Doe after John Doe?

Thanks in advance for your help.

Code: Select all

$array = ("John Smith", "John Doe", "John Jones");

$spouse1 = "John Doe";
$spouse2 = "Jane Doe";

// I want array to be...
// $array = ("John Smith", "John Doe", "Jane Doe", "John Jones"); 
gprince66
Forum Newbie
Posts: 6
Joined: Tue Feb 14, 2012 11:55 pm

Re: Insert name into an array

Post by gprince66 »

Solved

Code: Select all

$array = array("John Smith", "John Doe", "John Jones");$spouse1 = "John Doe";$spouse2 = "Jane Doe";		function insert_after($array,$search,$add){	$key = array_search($search,$array);	if($key !== false)	{		array_splice($array,$key+1,0,array($add));	}	return $array;}$array = insert_after($array, $spouse1, $spouse2);
Post Reply