1. No Profile Picture
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2000
Posts
18
Rep Power
0
This is a really easy question, and is on of the most elementary programming tasks, but I've been working on it too long and gone blind. Please help out.
I'm trying to do a standard move-in-queue algorithm, something like this

Array (before) - 3 - 7 - 4 - 3 - 8 - 9 - 2
Array (after) - 3 - 7 -new- 4 - 3 - 8 - 9
e.g. where new is inserted into the array at position 3 (\$position)

The (non-functinal) routine I'm using is :

for (\$i = 14;, \$i >= \$position; \$i--)
{
aktrow[\$i+1]=\$aktrow[\$i];
}

2. No Profile Picture
Carpe Diem
Guest
Devshed Newbie (0 - 499 posts)
Off the top of my head (And I know there is a better way but this was the first method that came to me)
<?
//Set position and text to insert
\$insert_text="boo";
\$insert_position=3;

//Create original array
\$aktrow = array (a,b,c,d,e,f,g,h,i,j,k);

//Reset temp array
\$tmparray = array('');

//Reset Array counter
\$count=0;

while (list(\$num,\$list) = each (\$aktrow))
{
if(\$num==\$insert_position)
{
\$tmparray[\$count] = \$insert_text;
\$count++;
\$tmparray[\$count] = \$list;
\$count++;
}else
{
\$tmparray[\$count] = \$list;
\$count++;
}
}

//Reset original array
\$aktrow = array ('');

//And recreate
while (list(\$num,\$list) = each (\$tmparray))
{
\$aktrow[\$num] = \$list;
}

//Just to prove it has updated
while (list(\$num,\$list) = each (\$aktrow))
{
echo \$list;
}
?>

Just a method that works

------------------

Regards
Darren
--
http://www.php4hosting.com/ \$
http://www.php4hosting.co.uk/ £
PHP/MySQL Enabled Hosting/Dedicated Servers
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2000
Posts
114
Rep Power
18
If'n you're using PHP4.x then you might want to try the built in function: array_splice.

Here's a quick example:
<BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">code:</font><HR><pre>
<?
\$tmp=Array(1,2,3,4,5,6,7,8,9);
array_splice(\$tmp,3,0,"new");
echo join(",",\$tmp);

//outputs 1,2,3,new,4,5,6,7,8,9
?>
[/code]
The function's signature looks like this:
array_splice(input_array,offset,length, replacement_array_or_string). If you use length 0 then it basically just inserts the replacement at the specified position.