Re: A problem with associative arrays..
| From: | Andreas Pour | Date: | Sat, 29 Jul 2000 19:31:17 +0000 |
| Subject: | Re: A problem with associative arrays.. | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-8982@lists.php.net to get a copy of this message | ||
Rasmus Lerdorf wrote:
>
> There is no solution. Rethink the way you are doing things.
I can think of a solution, involving a bit more code (of course you only
need to use this where you are not sure of the dimensions of the array):
What you want to do is:
$conf['db']['host'] = "dbhost";
But if $conf['db'] is a string, this does not work. So instead, use:
if (!isset($conf['db']) || !is_array($conf['db']))
$conf['db'] = array();
$conf['db']['host'] = "dbhost";
You can turn it into a function:
function setArray(&$array, $key, $value)
{
if (!isset($array) || !is_array($array))
$array = array();
$array[$key] = $value;
}
And call it as:
setArray($conf["db"], "host", "dbhost");
For example:
setArray($conf, "db", "testdb");
var_dump($conf);
setArray($conf, "db", "second_testdb");
var_dump($conf);
setArray($conf["db"], "host", "third_testhost");
var_dump($conf);
setArray($conf, "db", "fourth_testdb");
var_dump($conf);
Outputs:
array(1) {
["db"]=>
string(6) "testdb"
}
array(1) {
["db"]=>
string(13) "second_testdb"
}
array(1) {
["db"]=>
array(1) {
["host"]=>
string(14) "third_testhost"
}
}
array(1) {
["db"]=>
string(13) "fourth_testdb"
}
I do this as a habit w/ 2-D arrays anyway.
Ciao,
Andreas
>
> -Rasmus
>
> On Fri, 28 Jul 2000, Lez Lytollis wrote:
>
> > Did anyone come up with a solution for this? - I'm having exactly the same
> > problem at the moment.
> >
> > Cheers
> > Lez
> >
> > ----- Original Message -----
> >
> > > > > He's not defining it as a string. He's accessing it as an array.
> > > > > Does it still apply? What if he defined $conf to be an array
> > > > > prior to this?
> > > >
> > > > Think of it this way:
> > > >
> > > > $conf['db'] = "testdb";
> > > >
> > > > Now, when you try to assign something to $conf['db']['host']
> > > > the
> > > > $conf['db'] part is "testdb", what would
> > > > "testdb"['host'] be? Since
> > > > $cond['db'] is a string, the 'host' index of this string is
> > > > the same as
> > > > "testdb"[0] which is the first position of the string. So when you
> > > > do:
> > > >
> > > > $conf['db']['host'] = "dbhost";
> > > >
> > > > You end up with, "destdb", because there is only room for the first
> > > > character of "dbhost" in the $conf['db'][0] slot.
> > >
> > >
> > > I guess I just have to fix up a work around to this. :)
> > >
> >
> >
> >
> >
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net
> For additional commands, e-mail: php-general-help@lists.php.net
> To contact the list administrators, e-mail: php-list-admin@lists.php.net