• 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
https://www.neowin.net/forum/topic/1053231-php-array-indexes-as-string-value/
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. :)

  • 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?

  • 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?

  • 0
  On 06/02/2012 at 17:55, Jayzee said:

Templating engine.

Instead of reinventing the wheel why don't you use something like http://twig.sensiolabs.org/ ?

One of the most widely used, arguably the best templating engine for professional developers, you can't go wrong with twig.

  • 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 :)

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

    • No registered users viewing this page.
  • Popular Now

  • Posts

    • how am i gonna teach my grandma understand a new OS now ?
    • Well, Satya Nadella did say 30% of Microsoft's code is written by AI. Considering that code is also reviewed and tested by the same AI: garbage in, Microsoft code out.
    • Spotify 1.2.66.445 by Razvan Serea Spotify for Windows is your ultimate music and podcast streaming app, designed for a seamless listening experience. Enjoy millions of songs, curated playlists, and personalized recommendations tailored to your taste. Spotify delivers high-quality audio streaming with bitrates up to 320 kbps for Premium users and 160 kbps on the Free tier. Music is streamed in Ogg Vorbis format on the app and AAC on web browsers, ensuring efficient delivery and compatibility. Adaptive bitrate technology adjusts quality based on network conditions, while Premium users enjoy offline downloads for uninterrupted playback. Podcasts are streamed at slightly lower bitrates, typically 96-128 kbps, to balance quality and data usage. Spotify works across smartphones, desktops, smart speakers, game consoles, and more, with Spotify Connect enabling smooth cross-device playback. Features like real-time lyrics, curated playlists, and personalized EQ settings elevate the listening experience, making Spotify a versatile platform for music and podcasts alike. Spotify Free features: Stream Millions of Songs - Access a vast library of music across various genres and artists. Curated Playlists - Discover ready-made playlists for every mood and moment. Shuffle Play Mode - Enjoy songs in random order with shuffle-enabled playback. Personalized Recommendations - Get music suggestions based on your listening habits. Access to Podcasts - Explore a wide range of podcasts on topics you love. Ad-Supported Listening - Stream music with occasional audio and display ads. No Subscription Required - Enjoy music without any payment commitment. Cross-Device Sync - Listen seamlessly on mobile, desktop, or web browser. Basic Playback Controls - Play, pause, and skip tracks within shuffle limitations. Discover Weekly & Release Radar - Stay updated with custom playlists for new music. Download: Spotify 1.2.66.445 | ARM64 | ~100.0 MB (Free, paid upgrade available) View: Spotify Website | Web Player Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Understandable, they need to make money somehow to keep the service "free". If you're not paying with money, you'll pay with something else. In this case, it's ads. People will bitch about this (as usual), but it's basic economics, everything has a price, like YouTube (non-premium).
    • A sign of a man with absolutely no taste. Also the first American president to whine about American "jobs" while selling Chinese stuff for 5x or 10x the actual worth while slapping his stupid name on it. Like, what even is this, some really bad, humorless parody? Nope, it's the actual reality. Selling Chinese bible, selling EV's on White House front yard, selling Chinese phones that are wrapped in few microns of gold for 3x the value... It's so hilarious it's cringy af.
  • Recent Achievements

    • Week One Done
      patrickft456 earned a badge
      Week One Done
    • One Month Later
      patrickft456 earned a badge
      One Month Later
    • One Month Later
      Jdoe25 earned a badge
      One Month Later
    • Explorer
      Legend20 went up a rank
      Explorer
    • One Month Later
      jezzzy earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      637
    2. 2
      ATLien_0
      278
    3. 3
      +FloatingFatMan
      171
    4. 4
      Michael Scrip
      156
    5. 5
      Steven P.
      128
  • Tell a friend

    Love Neowin? Tell a friend!