• 0

[PHP] Array indexes as string value


Question

Hi guys,

I wonder why I'm not able to use strings as array index to get a value from the array?

Is there any other way of doing it (without evals please)?

Example:


$arr = array(
"foo" => array(
"bar" => "abc",
"baz" => "CBA"
)
);

$string = "['foo']['bar']";
echo $arr['foo']['bar']; // OK: abc
echo $arr{$string}; // Fail: Undefined index: ['foo']['bar']
[/CODE]

Link to comment
Share on other sites

7 answers to this question

Recommended Posts

  • 0

You can use strings as array indices, but you're also trying to use the strings as a substitute for the language.


<?php
$array = array(
'foo' => array('bar' => 'boz')
);
$foo = 'foo'; $bar = 'bar';
echo $array[$foo][$bar]; //boz
[/CODE]

You could capture the array keys though, but I'd guess that if you expand upon what you're trying to do there will be a better solution. :)

Link to comment
Share on other sites

  • 0

What Anthony said. You can't replace the syntax with your own strings.

It's like saying:

$function_end = ()

some_function$function_end;

Just doesn't make sense to me. Do it the proper way.

Or maybe you're doing something wrong in the first place, nothing should make you want to replace the syntax itself.

What are you trying to do?

Link to comment
Share on other sites

  • 0

I think this is what you're trying to do...


<?php
$array = array (
"foo" => array(
"bar" => "abc",
"baz" => "CBA"
)
);

$name = "['foo']['bar']";
var_dump ($array . $name);
?>
[/CODE]

With the code $array[$string] you are basically trying to find $array[['foo']['bar']]; which is invalid, whereas by printing it as $array . $name, it becomes $array['foo']['bar'];

Bad explanation, but I hope you understand :)

[b]Edit[/b]

Damn! I just noticed that code doesn't even work. The code I provided now echos Array['foo']['bar'];

[b]Edit #2[/b]

On further research, and asking other PHP programmers, we don't think it's possible and aren't really sure why you would want to do it this way. If you can give us an example of how your template system works, we may be able to help you with another system to grab the template data?

Link to comment
Share on other sites

  • 0

Yes, I looked into every templating engine available for PHP (incl. Twig) and found them bloated with bunch of extras I don't need, therefore I decided to create my own templating engine (I have already developed file caching engine which works just great and which templating engine now uses). I have analyzed source of most popular templating engines and created my own mini-templating engine based on best practices learned by analyzing source and reading articles (improving your skills as a developer is also a big +). I no longer use method array-replace method I asked about earlier :)

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.