Ok this might sound like a dumb question but bear with me. I am trying to make it so that when people go to example.php?id=1, example.php?id=2, example.php?id=3 etc they see different data called from an included file filling in the blanks.
I have a variable called $offername and I want to display $offer1name, $offer2name, $offer3name in that space, depending on what $_GET['id'] says. Ideally, when someone goes to example.php?id=2, $offername will equal $offer2name.
I want to do something like this:
$offername = $offer.$_GET['id'].name
But of course that doesn't work. What should I do?
A much cleaner solution is to just use multidimensional arrays.
e.g., instead of
$offername = ${offer.$_GET['id'].name};
use
$offername = $offer[$_GET['id']]['name'];
and define $offer like so:
$offer = array(
1 => array(
'name' => 'firstoffer',
),
2 => array(
'name' => 'secondoffer',
),
3 => array(
'name' => 'thirdoffer',
),
);
I find variable variables difficult to read, and most of the time when I see them used, an array would be much better.
This should work:
$var = 'offer' . $_GET['id'] . 'name';
$offername = $$var;
See the page on variable variables for more.
PHP can use variable variables
So you can have $offer_variable_name = 'offer' . $_GET['id'] . 'name';
And then use something like $offername = $$offer_variable_name.
You can in addition to the other solutions do:
$offername = ${'offer' . $_GET['id'] . 'name'};
Related
$fidimp = implode('"', $fidarr);
$friendsimp = implode('<a href="../profile?id=', $funamearr);
$impglue = '</a><br />' . $fidimp . '>';
echo('<a href="../profile?id=' . $fidimp . '>' . implode('</a><br />', $funamearr));
This is the code I'm working with.
$funamearr has 2 values in it: "Conner" and "Rach667"
$fidarr has 2 values in it as well: "2" and "3" (the user's id's)
When this code is run, it only makes "Conner" a link (it works, by the way) How can I make it so that "Rach667" shows up as a link too?
First build an associative array from your ids to your names, then create an array of links and implode it, something like:
<?php
$funamearr = array( "Conner", "Rach667" );
$fidarr = array( 2, 3 );
$users = array_combine($fidarr, $funamearr);
foreach($users as $id => $name) {
$links[] = sprintf('%s', $id, $name);
}
echo implode('<br/>', $links);
Well I don't recommend using implode in this case but as said by LokiSinclair to use a loop.
<?php
foreach($funamearr as $key => $value) {
echo '' . $value . '<br/>";
}
This case assumes that the array keys of $funamearr and $fidarr match with eachother.
Outside the code I would make two tips.
1 Use usefull variable names.
$funamearr is not telling me much, except the arr part because it probably is an array. I would recommand $usernames (multiple so array ;)
2 Keep data together
No we have to hope that the keys are the same. but if you keep the data at the same level we won't and ofter easier in use
ie
array(
array(
'id' => 1,
'name' => 'test',
),
array(
'id' => 2,
'name' => 'test_name_2',
),
)
First of all, my grouping is working but I feel it is dirty. Need someone to make it looks
clean and better.
I have following foreach
$data['new_array'] = array(); //I have to use $data['new_array'] because I need to pass it to template.
foreach ($get_topics as $topic) {
//Is that possible to make these 4 lines shorter?
$data['new_array'][$topic['tid']]['tid'] = $topic['tid'];
$data['new_array'][$topic['tid']]['title'] = $topic['title'];
$data['new_array'][$topic['tid']]['yes'] = $topic['yes'];
$data['new_array'][$topic['tid']]['no'] = $topic['no'];
//The belows are subarray grouping, it actually works but I need better solutions
//$new_array[$topic['tid']]['vid'][$topic['vid']][] = $topic['vid'];
//$new_array[$topic['tid']]['vid'][$topic['vid']][] = $topic['yesno'];
}
I wouldn't even try to make it shorter, but here's your code in a good looking version.
$data['new_array'] = array();
foreach ($get_topics as $topic) {
$data['new_array'][$topic['tid']] = array(
'tid' => $topic['tid'],
'title' => $topic['title'],
'yes' => $topic['yes'],
'no' => $topic['no']
);
}
Not sure what type is $topic['tid'] but you should be careful when using non-consecutive numbers as array keys.
Here are the variables:
$fake= 'cool';
$fake1 = 'not cool';
$hope= '1';
The idea is to combine $fake and the $hope to create the variable $fake1. The idea is that if the $hope variable was randomized it could generate a random variable: $fake1, $fake2, $fake3, etc. Right now I either get an error or just the values of $fake and $hope next to each other not the new variable.
You should use an "array" for this:
$list = array('cool', 'not cool');
$random_item = array_rand($list);
Using variable-named variables is always messy and this is exactly what arrays are for.
Ben's comment above does probably exactly what you're looking for, but if you're in PHP5 you can also do something like:
$varname = $fake . $hope;
$$varname = "horray";
You can try
$fake = array(
"fake1" => "Cool",
"fake2" => "Bad",
"fake3" => "Fish",
"fake4" => "Next",
"fake5" => "Wow");
list($a, $b) = array_rand($fake, 2);
echo $fake[$a] . " " . $fake[$b]; // This would always change
How can I include an string in an array?
emailconfig.php
$globalemail 'info#site.com'=>'site'";
I want to make a new array like this:
sendemail.php
include "emailconfig.php"
$fulllist=array('info#forum.com'=>'forum', '$globalemail');
// the Array MUST must appear above, ideally it would look like this
// $fulllist=array('info#forum.com'=>'forum', 'info#site.com'=>'site');
It brings PHP error because of the =>
One way is: in your emailconfig.php, you should have 2 variables, $globalemailkey and $globalemailvalue.
$globalemailkey = 'info#site.com';
$globalemailvalue = 'site';
$fulllist = array('info#forum.com'=>'forum', $globalemailkey => $globalemailvalue);
Or, store an array in emailconfig.php, and use array_merge.
$globalemail = array('info#site.com' => 'site');
$fulllist = array('info#forum.com'=>'forum');
$fulllist = array_merge($fulllist, $globalemail);
$fulllist=array('info#forum.com'=>'forum');
$globalemail = "info#site.com'=>'site'";
$parts = explode('=>', $globalemail);
$fulllist[trim($parts[0], "'")] = trim($parts[1], "'");
http://ideone.com/mmvu9
You could But You Shouldn't use eval to do something like eval("array($yourstring)");. But you shouldn't. really. please.
You can do all sorts of things like preg-match or explode, but couldn't you easier find the source of those pieces of information, and work from there?
Thanks for the help below, however, I'm still having some problems, I'll try and explain further:
I have a variable as follows:
$value['questions'];
Now, I need to do a check in a loop, so I have this piece of code in the loop:
if($results[$value['questions']]==4){blah blah blah};
but the problem I am having is that the value of $value['questions'] is q1 but I need the q1 to be a string (i.e. inside quotes '') in the $results section of the code, so the $results element should look like this...
if($results['q1']==4){blah blah blah};
currently it looks like this
if($results[q1]==4){blah blah blah};
Make sense?
Thanks again for the help.
Hi all,
I hope there is a simple solution!
I have a variable:
$results['q1'];
Is it possible to have the 'q1' element as a variable, something like this:
$results['$i[question]'];
Have not been able to find a solution on Google and researching the PHP manuals...
Anyone got a suggestion/ solution?
Thanks,
Homer.
Yes, it is possible to use a variable as indice, when accessing an array element.
As an example, consider this portion of code :
$results = array(
'a' => 'sentence a',
'b' => 'hello !',
);
$indice = 'a';
echo $results[$indice];
Which will give the following output :
sentence a
Here, $indice is a quite simple variable, but you could have used whatever you wanted between the [ and ], like, for instance :
functions : $results[ my_function($parameter) ]
array element : $result[ $my_array['indice'] ]
Which seems to be what you want to do ?
object property : $result[ $obj->data ]
...
Basically, you can use pretty much whatever you want there -- as long as it evaluates to a scalar value (i.e. a single integer, string)
In your specific case, you could have $results declared a bit like this :
$results = array(
'q1' => 'first question',
'q2' => 'second question',
);
And $i would be declared this way :
$i = array(
'question' => 'q1'
);
Which means that $i['question'] would be 'q1', and that the following portion of code :
echo $results[ $i['question'] ];
Would get you this output :
first question
Edit : To answer the specific words you used in the title of your question, you could also use what's called variable variable in PHP :
$variable = 'a';
$indice = 'variable';
echo $results[ $$indice ];
Here :
$indice is 'variable'
and $$indice is 'a'
which means you'll get the same output as before
And, of course, don't forget to read the Arrays section of the PHP manual.
The Why is $foo[bar] wrong? paragraph could be of interest, especially, considering the example you firt posted.
Edit after the edit of the OP :
If $value['questions'] is 'q1', then, the two following portions of code :
if($results[$value['questions']]==4){blah blah blah}
and
if($results['q1']==4){blah blah blah}
should do exactly the same thing : with $results[$value['questions']], the $value['questions'] part will be evaluated (to 'q1') before the rest of the expression, and that one will be the same as $results['q1'].
As an example, the following portion of code :
$results = array(
'q1' => 4,
'q2' => 6,
);
$value = array('questions' => 'q1');
if($results[$value['questions']]==4) {
echo "4";
}
Outputs 4.
You can do:
$results[$i['question']];
This will first access the array $i to get the value corresponding to the key 'question'. That value will be used as the key into the array $results.
Your way: $results['$i[question]'];
is actually trying to get the value corresponding to the key '$i[question]' in the array $results. Since the key is in single quote, variable interpolation does not happen and the entire string is treated literally.
Alternatively you can also do:
$results["$i[question]"]; // using double quotes also works.
Example:
$arr1 = array('php' => 'zend', 'java' => 'oracle');
$arr2 = array('p' => 'php', 'j' => 'java');
echo $arr1[$arr2['p']]; // prints zend.
echo $arr1["$arr2[p]"]; // prints zend.
<?php
$result['q1'];
// is equivalent to
$index = 'q1';
$result[ $index ];
Now $index can be as complex as you want it to be. For example something like this is also possible:
$result[ 'q' . round( $someArray[$i] / 2 ) ];
CODE
<?php
$results = array(
'q1' => 'This is a result called q1.',
'q2' => 'So, can you access this?',
'$i[question]' => 'This is a result called $i[question]',
);
$i = array(
'question' => 'q2',
'answer' => 'Yes.'
);
echo '<pre>';
echo $results['q1'] . "\n"; // Using Array's is easy -
echo $results['$i[question]'] . "\n"; // all you gotta do is make sure
echo $results[$i['question']] . "\n"; // that you understand how
echo $i['answer']; // the keys work.
?>
OUTPUT
This is a result called q1.
This is a result called $i[question]
So, can you access this?
Yes.