...

View Full Version : Inserting Values In Array



thekevin07
03-08-2007, 10:36 AM
Hi

Does anyone know how to insert values into an array? For example i have an array called $array with orange green blue Black in that order how do i insert red in between green and blue?

Thanks

chump2877
03-08-2007, 11:19 AM
This is one way...I'm assuming your using numbered indices:


<?

$my_array = array("orange","green","blue","black");

foreach ($my_array as $val)
{
if ($val == "blue")
$my_array2[] = "red";
$my_array2[] = $val;
}

$my_array = $my_array2;
var_dump($my_array);

?>

Inigoesdr
03-08-2007, 06:40 PM
This is another way you can do it:

$search = 'green';
$after = 'red';
$my_array = array('orange','green','blue','black');
array_splice($my_array, array_search($search, $my_array), 1, array($search, $after));
var_dump($my_array);

thekevin07
03-08-2007, 09:05 PM
Thanks for responding. Any idea as to how i can apply that to a user supplied number and when i get 3 place values it inserts a comma?

chump2877
03-09-2007, 01:42 AM
If I understand you right, instead of splitting up your multi-digit, user-supplied number into an array of one-digit numbers, just use number_format (http://us3.php.net/manual/en/function.number-format.php)() to format your numbers.

thekevin07
03-09-2007, 02:10 AM
Thats perfect!!! Thanks!!!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum