Array question....

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
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Array question....

Post by Todd_Z »

If i have an array... lets say

Code: Select all

<?php
$ar = array ( "One", "Two", "Four", "Five" );
?>
How do I put "Three" in between two and four?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

from php.net
I needed a function to add data to a particular place in an array without loosing any other data in the array. Here it is:

Code: Select all

<?php
function insert_into_array($array,$ky,$val) 
{ 
 $n = $ky; 
 foreach($array as $key => $value) 
   { 
     $backup_array[$key] = $array[$key]; 
   } 
 $upper_limit = count($array); 
 while($n <= $upper_limit) 
   { 
     if($n == $ky) 
       { 
     $array[$n] = $val; 
     echo $n; 
       } 
     else 
       { 
     $i = $n - "1"; 
     $array[$n] = $backup_array[$i]; 
       } 
     $n++; 
   } 
 return $array; 
} 
?>
Post Reply