• 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

    • I know Windows DHCP and DNS servers get teased a lot, but those services were at least created at a time when MS cared more than they do now, and they work mostly as expected. I actually use both in a multisite professional setting, not really because I love them, but because we use Active Directory and those services go hand-in-hand with it. A few times when I have needed to configure some more advanced features, I was worried Windows might not support them, but so far it has not let me down. I can only image the horror a Windows 11 era DHCP server would be, probably fewer options than the basic service on a Netgear router.
    • Since the article doesn't cover it: >Pinned Tabs allow you to always keep your favorite tabs open and just a click away. Pinned Tabs are small, can't be closed accidentally, and open automatically when you start Firefox. from https://support.mozilla.org/en...keep-favorite-websites-open
    • CapCut 6.4.0 (offline installer) by Razvan Serea CapCut is a versatile video editing app that offers a range of features such as multi-layer editing, keyframe animations, special effects, and more, to create professional-quality videos. With CapCut, users can edit and enhance their videos with a variety of tools such as filters, transitions, effects, and text overlays. CapCut's extensive library of pre-designed templates and visual effects also allows users to create unique and eye-catching videos in just a few clicks. Users can also adjust video speed, crop, and merge multiple clips, among other features. CapCut is available for both mobile devices and Windows, making it accessible for everyone. CapCut key features: User-friendly interface for easy video editing A wide range of editing tools, including trim, split, cut, and merge Music library with a wide range of tracks to choose from Customizable text and fonts to add captions and titles Multi-layer timeline for seamless editing and layering Filters and effects to enhance video quality and style A variety of transitions to choose from Multiple aspect ratio options for different platforms Green screen/chroma key for adding custom backgrounds Overlays and stickers to add to your videos Easy exporting to different video formats and resolutions Large library of pre-designed templates and visual effects Customizable video thumbnails for branding Keyframe animation to add movement to your video Speed adjustment for slow motion or time-lapse effects Customizable transitions between clips Reverse video playback for creative effects Voiceover recording and editing for narrating your video Color grading tools and much more... Download: CapCut 6.4.0 | 709.0 MB (Freeware) Links: CapCut Website | CapCut Screenshot | CapCut Online Editor Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I love how everything is gold except the Trump name, which is usually gold. It's in red, but the US flag? No blue or red allowed. This is such a hack Photoshop job, I would have thought Jony Ive was behind it. But even he wouldn't show art this unfinished. Just this stupid.
    • >Unlimited talk time, messages, and internet As Captain Picard once said to the android nearby, "Data?"
  • 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
      640
    2. 2
      ATLien_0
      279
    3. 3
      +FloatingFatMan
      170
    4. 4
      Michael Scrip
      156
    5. 5
      Steven P.
      131
  • Tell a friend

    Love Neowin? Tell a friend!