PDA

View Full Version : Problem with Array Insertion


xushi
6-19-05, 11:51 PM
Can anybody tell me, what it's wrong with following code:

<?
function addArray($array,$key,$val) {
$tempArray = array($val => $key);
$array = array_merge($array,$tempArray);
return $array;
}

$xarray = array();
$xarray = addArray($xarray,'1','X');
$xarray = addArray($xarray,'11','Y');

foreach (array_keys($xarray) as $key=>$val)
{
echo "key = ".$key." val = ".$val."<br>";
}
?>

It prints following result of array:
key = 0 val = X
key = 1 val = Y

But I'm expecting somethiong like:
key = 1 val = X
key = 11 val = Y

Can anybody tell me, how can I insert a new entry with a specified key into an existing array.

thanks,

RTH10260
6-20-05, 01:00 PM
Can anybody tell me, what it's wrong with following code:

[ ... ]

It prints following result of array:
key = 0 val = X
key = 1 val = Y

But I'm expecting somethiong like:
key = 1 val = X
key = 11 val = Y

Can anybody tell me, how can I insert a new entry with a specified key into an existing array.

thanks,First, I don't quite see what you intend to do with this coding exercise of yours. Doesn't one of the other array functions get your task completed better ?
Ref: http://www.php.net/manual/en/ref.array.php

Or this code appends an array to the end too:$xarray = array();
$xarray[] = array('1','X');
$xarray[] = array('11','Y');
But back to your actual question:
You are creating an array of an array. The outer array you are appending to. be it your method or mine, adds a new array element without any key to the container, eg the default is a zero based key as listed by your code snippet.

To list the content of the inner array, you need to use a second nested iterator:foreach ($xarray as $outerkey=>$outerval) {
echo "outerkey = ".$outerkey."<br>";
foreach ($outerval as $innerkey => $innerval) {
echo " innerkey = ".$innerkey." innerval = ".$innerval."<br>";
}
}