Jul 27, 2008

Getting An Array Value Of A Dynamic Variable

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > PHP Programming

free web hosting

Getting An Array Value Of A Dynamic Variable

galexcd
Ok i can't believe I need help in php but I can't figure this out... If i have an array, lets say called test, how do i get a certain value from that array when referencing it dynamically by either a string or another variable?

Example:
CODE
$test=array(1,2,5);
$name="test";
//Doesn't work:
echo $$name[0];
/Doesn't work:
echo ${$name}[0];

Reply

jlhaslip
CODE
<?php
$test=array(1,2,5);
$name = &$test; // check this line

echo 'print_r $test';
echo '<br />';
echo '<pre>';
print_r ($test);
echo '</pre>';
echo '<br />';

echo 'print_r $test[0]';
echo '<br />';
print_r ($test[0]);
echo '<br />';

echo '<br />';
echo 'print_r $name';
echo '<pre>';
print_r ($name);
echo '</pre>';

echo '<br />';
echo 'print_r $name[0]';
echo '<pre>';
print_r ($name[0]);
echo '</pre>';

?>


Note line 2 and the prefix for references, compared to your code.

Reply

galexcd
I was hoping not to use references but all right i guess i must...

Reply

pointybirds
Alex,

I believe the evil eval could be your friend here:

CODE
$test=array(1,2,5);
$name="test";
eval ("\$blah = $${name}[2];");
echo $blah;


Use it with care and good luck!

Reply

galexcd
Does eval parse differently than regular php code? I always assumed it was the same. I shall try this and report back here if it works.

Reply

pointybirds
eval will run the contents of the string as code, however it interpolates variables too, so the above code will replace $name with "test", then uses $test in the eval.

Reply

pop
i test you code, work. my version php 5.2

CODE
<?php

$test=array(1,2,5);
$name="test";

echo ${$name}[2]; // print 5 ?!

?>

Reply

galexcd
Hmm it didn't work for me... Perhaps its because I have an older version?

Reply

jlhaslip
works for me, too

php 5.2.4

Reply

pop
you can see php version if you run

<?php phpinfo(); ?>

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : array, dynamic, variable

  1. Unexpected T_variable...
    Help! (3)
  2. Remove A Value From A Php Array Based On Its Value
    (5)
    I have an index array CODE $array[0] = 10; $array[1] = 12; ...
    Its kinda late and I'm falling asleep now but I had a quick look through PHP.net, and could not
    find what I'm after, Maybe I'm too sleepy, sorry, but if anyone knows off the top of their
    head a way to removed members in that array based on its value, i.e. I wanna remove values 12. I
    don't really want to do a loop but if I cant find any existing function to do it, then I may
    have to. Thanks for any help.....
  3. Script Help Required: Undefined Variable
    A fault I cannot spot in PHP (3)
    Hi, when running a PHP script I keep getting the error: QUOTE Notice: Undefined variable: bret
    in c:\program files\easyphp1-8\home\poll.php on line 294 Notice: Undefined
    variable: bret in c:\program files\easyphp1-8\home\poll.php on line 294 (And,
    yes, I get it twice). The code related to the variable is as follows: CODE function
    LogString($string,$type)     {         $t_log = "\n";
            $t_log .=
    $this->globaldata->server_vars['REMOTE_ADDR']."....
  4. Using Multiple Selection Array In Table To Order Data
    Using multiple selection array in table to order data (1)
    have a form that has a multiple select choice, like this: CODE <form method="post"
    action="display.php" <select multiple name="selectsort[]">
    <option value="code">Code</option> <option
    value="amount">Amount</option> <option value="dateammended">Date
    Ammended</option> <option value="expreviewdate">Expiration/Review
    Date</option> <option value="effectivedate">Effective Date</option>
    <option value="e....
  5. Trap17 Board Status Dynamic Image
    (13)
    I was really board a few days ago and decided to make a trap17 board status image for my sig
    /tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" /> That is the
    current beta. I'm still working on it so that it might display the most recent post or
    somthing, i'm not sure. After I finish it ill give out the source code but if you want one
    right now you can pm me and ill set one up to get the info on your account ^.^ So I was wondering
    how you members liked it? You'll probably think that its a waist of time, but alas as I sai....
  6. Can I Make Dynamic Menu In Php
    is it posible to make dynamic menu in php without javascript (7)
    As there are many java script by which we can have event based interaction like,message on mouse
    over etc,that we can create dynamic menu in javascripts to make navigation bar ,but is it possible
    in php to have this acomplished without javascripts,i am new to php,is it possible?. Thanks....
  7. Reading Files From Directory To Array, And Using $_get To Get Them
    Simple way to manage lot's of files (2)
    Some user posted a similar problem i had when i tried to figure out how to update content on my
    website in less work as possible. This is just part of the "big" plan i have for my site but it can
    be helpfull to you guys if you like FlatFile. I hope that mod's don't mind me posting the
    same code here and on their forums, couse if they do i'll delete it from their forums
    /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> So
    here's the situation. Let's say you have a folder called 'myfilesdirectory' on your
    s....
  8. More Dynamic ?id=browsing With Php (associative Array)
    Just create array and watch php code do the rest (1)
    The thing that has been bugging me for a while was that switch statement that we use to create ID
    browsing (some use If-Ifelse but results are the same for both). I wanted to figure out a way to use
    more dynamic switch statement so that i only need to update my links array in order to create links
    for template. With use of foreach, array_keys, and in_array functions finally i managed to do so.
    Also i'm planing on changing foreach with array_walk but i'll do that later. Now for the
    code.. First we create an associative array something like this CODE $gl....
  9. Dynamic Php Pages
    Nice tutorial (5)
    This is a really good tutorial on making php pages that normally appear as
    www.domainname.com/links.php appear as www.domainname.com/index.php?page=links
    http://nuwen.com/tutorials/php-dynamic-pages ....
  10. Php Form Help!
    Parse error T_LNUMBER - expecting T_VARIABLE (3)
    Hello, I am trying to make an employee application. I was just wondering if anyone knows how to spot
    a php code error, when the code directly around the line with the error looks the same. below is
    some of my process.php code. I beleive the error is on line 41. QUOTE PHP parse error: PHP
    Parse error: parse error, unexpected T_LNUMBER, expecting T_VARIABLE or '$' in
    /home/wwwange/public_html/FORMS/forms/process.php on line 41 Process.php code: CODE
    <?php include("global.inc.php"); $errors=0; $error="The foll....
  11. Spliting An Array
    (4)
    I got this excercise from school, im trying to understand it but im unable..can someone help me ?its
    very small problem but im not getting the point. ------------------ Create a string:
    $wholestring = “splitwholestring”; And split it to array using for loop. So that you have a
    array containing all the letters of the string: array == s, array == p, etc. Display results.
    (hint: strlen(), substr() - functions are useful) ------------------....
  12. Converting Characters In A Variable To Individual Values In An Array
    turning variables into arrays (2)
    Say I have a variable such as $nav_item and it had to contents Home . IE: CODE
    $nav_item = 'Home'; How would I make so that $nav_item was an array and
    had the following contents? CODE $nav_item = array ('h', 'o',
    'm', 'e'); With the case changing (ie H would become h and U
    would become u ) EDIT: Okay found out that I could change the case with
    array_change_key_case ($nav_item, CASE_LOWER); ....
  13. <textarea> Tag Is Not Accepting Php Variable
    for display, although <Input> tag does accept it (2)
    I have a single page template which has a Form on it. Logic is to check for a valid Querystring and
    place the variables accepted from a form back into the form and re-display this form with error or
    acceptance messages. I'm sure everyone here has done this a million times. The Form accepts
    data from a user for First name, Last name, email address, and message-body named
    'note_wide' then re-displays the values into the Form, but for some reason, I can't get
    the value to display into a Textarea. Sample of the php code is as follows: first the good one:....
  14. Dynamic Image / Signature Generator
    a simple code to change text on an image (12)
    In search of dynamically changing quote, saying or all other types of text on an image I came across
    a code that I have modified to fit my initial usage. This procedure requires two files and short
    knowledge of PHP. If you are familiar with Trap17's sig rotation code you will understand this
    procedure very fast. Code 1: dynamic_sig.php (you can rename this to index.php and you'll see
    at the end why) Code 2: a simple text file named anything (I will call it name.txt ) Code 1
    CODE <?php header("Content-type: image/png"); �....
  15. Dynamic Drop Down List <select>
    (3)
    Hi, What I am trying to achieve is when you have a form drop down menu, it displays all the
    categories from the directory, with all the indentations. Something like when you submit your site
    to a directory. Now I've got it almost working, but I can figure out how to indent it. The code
    below, I've used a spacer gif, but obviously that won't work! I've had a go at
    this, as you can see, but that does do the indentations, unless I'm doing something wrong here.
    Any help appreciated - thanks. PHP Code: CODE function maketree($root....
  16. Remove Objects From Array With Unset
    (2)
    Have been trying to solve this for a long time now, so I thought I´d give you guys a chance to break
    it! I want to remove an object from an array that I store in a Session object. I´ve written a
    function that takes an array and an id as parameters. Checks if one of the objects has the id I want
    to remove and then it´s supposed to remove it. Quite simple, that´s why I cant see why it doesnt
    work! Here´s the code: CODE function Remove_prod($id2,$AL) {
    print_r($AL); foreach ($AL as $prod) if($prod-....
  17. Dynamic Included Menus
    path specification (8)
    I am looking for a way to make a dynamic menu using php and include, basicly I want to make a file
    that contains html formating source and links and include it somewhere in all my pages, the problem
    is that links are taken literaly and refered to as to where the html is running from. So is there a
    way I can make a file and include it in my pages, then it will determin where the page is running
    from, and generate the links with an approperate amount of ../../'s so if my index is at root,
    but every section has it's own folder, I want to be able to include this fil....
  18. Determining Whether A Phrase Is In A Variable
    deciding whether a string is a url (2)
    I have a input box in a form called "button" and when the user clicks Submit! I want php to
    determine whether or not this is a url or just text. All urls have "http://" in them so I have
    decided I need a script which can determine whether or not "http://" is in a variable or a string.
    The problem with using strings is that I've never needed to use them before (and thus have no
    knowledge about them). When I was using asp, I knew there was a function called instr() but I
    can't find php's equivalent. Does anybody know? Thanks in advance!....
  19. Calling A False Variable...
    like $count . $val (6)
    Okay I'm very new to PHP still, although you may recognize me from the threa before, just go
    finished finals so now back to PHP! On one page I accept an input which will tell the next page
    how many form lines to generate, that part I have worked out, or so I think. Because the number of
    forum fields could vary I need to have a number of forum variables, so I used this code: CODE
    echo   "<td><input name=\"wname" . $appendval . "\"
    type=\"text\" id=\"wname" . $appendval . "....
  20. Php Parse Error
    Including Variable in post (2)
    ok this is my config script that runs my site: CODE <? # Set up info for left column on the
    top page: # It should begin with html tag <td> and finish with tag </td>
    $top_leftcol=" <td width='195' bgcolor='#eeeeee'
     valign='top'> <table width='100%'  bgcolor='#777799' border=0
    cellspacing='0' cellpadding='0'> <tr><td> <font
    FACE='ARIAL, HELVETICA' color='#ffffff' size='-1'>  
    <b>MMORPG Trade Center<....
  21. Stored Or Global Variable?
    (1)
    I've created a form, nothing special, that uses a php script as a form action to input data into
    mysql. Nothing special at all about this scenario. One thing I'd like to do is have the php
    script redirect the user back to the html page that has the form the user just completed. I
    don't want to have to hard code the url into the header function because I use this php script
    with a bunch of other pages. Does PHP store the value of this page into some variable that the php
    script can use? Thanks. kvarnerexpress....
  22. Php Dynamic News Updating Using Mysql
    changing a sites news using MySQL and PHP (3)
    Hey everyone. It appears to me that everyone really know what they are doing in this forum and im a
    pretty new to this PHP and MySQL combo. I know some PHP but not MySQL....I am trying to make a new
    website but i want to be able to go to a certain update page and change the news on the main index.
    For example: - The main page show news updates of the last 10 post. - I go to the update page
    and then fill in the form and it will add this post to the top of the list and still only print the
    top 10. I have no clue how to do this with MySQL. At the moment i am doing it u....
  23. Calling A Variable From A Dynamic List In A Sql Statement
    (2)
    I would be greatful if anyone could help me out, I have been stuck on this for a while. The problem
    is that I have a drop down menu which I get the contents of from a database. Then when I press the
    get details button I want to use the value selected in my drop down menu and pass it into an SQL
    statement to recieve all te relevent info. Everything works if I specify a known variable, but the
    problem seems to be passing a variable in which is part of the array. Below is the code for the drop
    down menu and the Sql statement i'm trying to execute. drop down menu: �....
  24. Possible To Put An If Statement Inside A Variable?
    (2)
    Ok, so I'm using the include() function on my website. Problem is I'm trying to include a
    search engine form into the layout which is stored in a variable, except the form has an if
    statement in it and I can't seem to get it working. Here's the code I'm trying to
    include... CODE Search: > Just wondering if it is possible for me to put this
    form with the if statement into a variable, or if there's another way that I could go about
    doing this. Thanks.....

    1. Looking for array, dynamic, variable

Searching Video's for array, dynamic, variable
Similar
Unexpected
T_variable..
. -
Help!
Remove A
Value From A
Php Array
Based On Its
Value
Script Help
Required:
Undefined
Variable - A
fault I
cannot spot
in PHP
Using
Multiple
Selection
Array In
Table To
Order Data -
Using
multiple
selection
array in
table to
order data
Trap17 Board
Status
Dynamic
Image
Can I Make
Dynamic Menu
In Php - is
it posible
to make
dynamic menu
in php
without
javascript
Reading
Files From
Directory To
Array, And
Using
$_get
To Get Them
- Simple way
to manage
lot's of
files
More Dynamic
?id=browsing
With Php
(associative
Array) -
Just create
array and
watch php
code do the
rest
Dynamic Php
Pages - Nice
tutorial
Php Form
Help! -
Parse error
T_LNUMBER -
expecting
T_VARIABLE
Spliting An
Array
Converting
Characters
In A
Variable To
Individual
Values In An
Array -
turning
variables
into arrays
<textarea
> Tag Is
Not
Accepting
Php Variable
- for
display,
although
<Input>
; tag does
accept it
Dynamic
Image /
Signature
Generator -
a simple
code to
change text
on an image
Dynamic Drop
Down List
<select&g
t;
Remove
Objects From
Array With
Unset
Dynamic
Included
Menus - path
specificatio
n
Determining
Whether A
Phrase Is In
A Variable -
deciding
whether a
string is a
url
Calling A
False
Variable...
- like
$count
. $val
Php Parse
Error -
Including
Variable in
post
Stored Or
Global
Variable?
Php Dynamic
News
Updating
Using Mysql
- changing a
sites news
using MySQL
and PHP
Calling A
Variable
From A
Dynamic List
In A Sql
Statement
Possible To
Put An If
Statement
Inside A
Variable?
advertisement



Getting An Array Value Of A Dynamic Variable



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE