Accessing value of an array, using an array as the indices

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
JeFFb68CAM
Forum Newbie
Posts: 15
Joined: Tue Apr 03, 2007 11:17 pm

Accessing value of an array, using an array as the indices

Post by JeFFb68CAM »

Hey there,

It's been a while since I posted here. Few years probably. I'm working on a project, and it would be really helpful if I could figure out a simple way of doing what I am about to describe.

What I am trying to do, is use array values as the access keys to another array, it will be easier for me to show you.

Code: Select all

$keys = array("db", "tables", "messagse");

$config = array(
	"db" => array(
		"tables" => array(
			"messages" => "messages_table",
			"users" => "users_table",
		),
		"settings" => array(
			"username" => "db username",
			"password" => "db password",
		),
	),
	"lang" => array(
		"etc......"
	)
);
Basically, I will have a large array that holds all of my config values, and because of how I have set my project up, I will get a lot of results like $keys in the above. What I would like to be able to do is figure out how to use $keys to map me to the result "messages_table" without using any sort of loop. So basically, I want $keys to become the ['db']['tables']['messages'] that I would throw onto the end of $config;

Temporarily, I've used this:

Code: Select all

$item  = $config;

foreach($keys as $k)
{
	$item = $item[$k];
}

// $item = "messages_table" (expected result)
Have I explained that adequately? It's a little difficult for me to explain, and it's been a long night for me so I might not be thinking sharply, but I am hoping someone here is maybe able to open a few windows for me and shine some light on an easy solution.

Thanks for any help,
Jeff
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Accessing value of an array, using an array as the indic

Post by Weirdan »

While you can't do this without eval(), you could wrap that loop into a function and use that:

Code: Select all

function array_path($array, $path) {
  $ret = $array;
  foreach ($path as $k) $ret = $ret[$k];
  return $ret;
}
$item = array_path($config, $keys);
JeFFb68CAM
Forum Newbie
Posts: 15
Joined: Tue Apr 03, 2007 11:17 pm

Re: Accessing value of an array, using an array as the indic

Post by JeFFb68CAM »

Yeah, that's how I have it setup right now (inside a function).

I was just hoping there was a better way to do it without using a loop every time I want to get a table name. I have my project setup to use chains, so it would be $this->config('db > tables > messages');

I rarely get frustrated enough to post somewhere for help, so I'm not surprised there's no better solution, thanks anyway!
Post Reply