PHP simple concatenation of dynamic vars - php

How do I join a dynamic var to an existing var?
For example:
My code:
<?
// Gets value from url. In this example c is 1.
$c = $_GET[c];
// Multiple static questions will be pulled from a list.
// I use two as an example below.
$Q1 = "Is this question one?";
$Q2 = "so this must be question two then?"
echo "$c: ";
echo "Q$c"; // returns "Q1" but not the string above.
echo '$Q.$c"; // returns the val 1
?>
How do I join the two together and get it to return the appropriate string?

Instead of dynamic variable names, use an array that holds multiple values.
$num = $_GET['c'];
$questions = array(
"Is this question one?",
"so this must be question two then?"
);
echo "$num: ";
echo "Q$num";
echo $questions[$num];
There are many, many reasons to prefer arrays to "variable variables". One is that it's a cinch to loop over all the items in an array:
foreach ($questions as $num => $question) {
echo "Q$num: $question\n";
}
Another is that you can calculate the size of an array.
echo "There are " . count($questions) . " total questions.";
Another is that you can easily modify them. There are lots and lots and lots of ways to manipulate arrays which you could never do with a crude tool like variable variables.
// Add a new question to the array.
$questions[] = 'Question 3: Who are you?!';
// Remove duplicate questions.
$questions = array_unique($questions);

It looks like what you're really looking for is an array:
$questions = array("Question 0", "Question 1", "Question 2");
$q = 1;
echo $questions[$q]; //"Question 1"
Otherwise, you're going to have to use some var-var nasty hackiness (don't do this):
echo ${'Q' . $c};
Also, $_GET[c] should be $_GET['c'] unless c is actually a constant (and I hope it's not since c would be a terrible name for a constant). And you should use isset rather than assuming that the c key exists in $_GET
Full example:
$questions = array("Question 0", "Question 1", "Question 2");
$c = (isset($_GET['c'])) ? (int) $_GET['c'] : null;
if (isset($questions[$c])) {
echo "The question is: " . $questions[$c];
} else {
echo "The question was not found";
}
You should probably also be aware of the draw backs of short open tags. If ever a server has them disabled, all of your PHP code is going to break. Typing 3 extra characters doesn't seem worth that risk. (Though it is of course really easy to just mass find/replace <? -> <?php.)

I'm not sure I get what you meant but I think this is the anwer:
<?php
$var = "Q".$_GET['c'];
echo $$var; // take care of the double dollar sign
?>
but arrays are more preferred of course

you can use php eval() function like this:
eval("echo \$Q$c;");
but you should be careful not to put user data without validating, because it can lead to security issues.

Related

php array syntax ${ is confusing me

I create a $values array and then extract the elements into local scope.
$values['status'.$i] = $newStatus[$i];
extract($values);
When I render an html page. I'm using the following
<?php if(${'status'.$i} == 'OUT'){ ?>
but am confused by what the ${ is doing and why $status.$i won't resolve
$status.$i means
take value of $status variable and concatenate it with value of $i variable.
${'status'.$i} means
take value of $i variable, append id to 'status' string and take value of a variable 'status'.$i
Example:
With $i equals '2' and $status equals 'someStatus':
$status.$i evaluated to 'someStatus' . '2', which is 'someStatus2'
${'status'.$i} evaluated to ${'status'.'2'} which is $status2. And if $status2 is defined variable - you will get some value.
I wanted to add to the accepted answer with a suggested alternate way of achieving your goal.
Re-iterating the accepted answer...
Let's assume the following,
$status1 = 'A status';
$status = 'foo';
$i = 1;
$var_name = 'status1';
and then,
echo $status1; // A status
echo $status.$i; // foo1
echo ${'status'.$i}; // A status
echo ${"status$i"}; // A status
echo ${$var_name}; // A status
The string inside the curly brackets is resolved first, effectively resulting in ${'status1'} which is the same as $status1. This is a variable variable.
Read about variable variables - http://php.net/manual/en/language.variables.variable.php
An alternative solution
Multidimensional arrays are probably an easier way to manage your data.
For example, instead of somthing like
$values['status'.$i] = $newStatus[$i];
how about
$values['status'][$i] = $newStatus[$i];
Now we can use the data like,
extract($values);
if($status[$i] == 'OUT'){
// do stuff
}
An alternative solution PLUS
You may even find that you can prepare your status array differently. I'm assuming you're using some sort of loop? If so, these are both equivalent,
for ($i=0; $i<count($newStatus); $i++){
$values['status'][$i] = $newStatus[$i];
}
and,
$values['status'] = $newStatus;
:)

Add two $row together in one php echo

I'm not even sure if what I am trying to do is possible, I have a simple php echo line as below..
<?php echo $T1R[0]['Site']; ?>
This works well but I want to make the "1" in the $T1R to be fluid, is it possible to do something like ..
<?php echo $T + '$row_ColNumC['ColNaumNo']' + R[0]['Site']; ?>
Where the 1 is replaced with the content of ColNaumNo i.e. the returned result might be..
<?php echo $T32R[0]['Site']; ?>
It is possible in PHP. The concept is called "variable variables".
The idea is simple: you generate the variable name you want to use and store it in another variable:
$name = 'T'.$row_ColNumC['ColNaumNo'].'R';
Pay attention to the string concatenation operator. PHP uses a dot (.) for this, not the plus sign (+).
If the value of $row_ColNumc['ColNaumNo'] is 32 then the value stored in variable $name is 'T32R';
You can then prepend the variable $name with an extra $ to use it as the name of another variable (indirection). The code echo($$name); prints the content of variable $T32R (if any).
If the variable $T32R stores an array then the syntax $$name[0] is ambiguous and the parser needs a hint to interpret it. It is well explained in the documentation page (of the variable variables):
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
You can do like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
$b = $$a;
echo "<pre>";
print_r($b[0]['Site']);
Or more simpler like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
echo "<pre>";
print_r(${$a}[0]['Site']);

array_intersect() Argument is not an array

I have developed this small code to check if 2 text, one from a database and the other from an outside imput have common words.
The problem is that I get a message "Argument is not an array".
I cannot see where is the problem.
I also need to check if the 2 messages if should have the same words are in the same sequence.
Please help to understand where is the mistake.
Thanks
$checkMsg=strip_tags($_POST['checkMsg']); // message from input form
$message // message from database
$MsgWords = preg_split("/[\s,]+/", $checkMsg);
if(!empty($checkMsg)){
foreach ($MsgWords as $Neword)
{ $Neword = trim($Neword);
echo " $Neword";
}
$word = preg_split("/[\s,]+/", $message);
foreach ($word as $currentWord)
{
$currentWord = trim($currentWord);
echo " $currentWord";
}
$intersect=array_intersect( $Neword ,
$currentWord);
echo" Your common words are: $intersect";}else{echo "No common words";}
As others have said you're comparing the strings not the array. Your code should be something like this (you'll have to probably change this a little its just an example)
$checkMsg=strip_tags($_POST['checkMsg']); // message from input form
$message // message from database
$MsgWords = preg_split("/[\s,]+/", $checkMsg);
if(!empty($checkMsg)){
$intersect=array_intersect($message,$MsgWords);
if (count($intersect)>1) {
//only show output if there are matches
echo "Words in common are:<br />";
foreach ($intersect as $Neword) {
$Neword = trim($Neword);
echo $Neword."<br />";
}
} else {
echo "There are no words in common";
}
}
Okay, so firstly you're looping through the two arrays and changing the value, but the way you have it, you are just changing a temp copy of the value, not the value in the array. To do that, you need to use the & sign in the foreach() to tell it to use a reference variable in the loop, like this:
foreach ($MsgWords as &$Neword) { //added the & sign here.
$Neword = trim($Neword);
}
Do the same thing to the other foreach() loop too.
Secondly, your array_intersect() call is looking at the single strings, not at the whole arrays. You need it to look at the arrays:
//your incorrect version:
$intersect=array_intersect( $Neword, $currentWord);
//corrected version, using your variable names.
$intersect=array_intersect( $MsgWords, $word);
That should solve your problems.
[EDIT]
Also, note the array_intersect() outputs an array (ie the array of the intersection between the two input arrays). You can't use echo() to print an array directly. If you try, it will just show the word 'Array'. You need to convert it into a string first:
//your incorrect code.
echo "Your common words are: $intersect";
//corrected code:
echo "Your common words are: ".implode(',',$intersect);
I would also note that your coding style is very messy and hard to read. I strongly recommend trying to tidy it up; follow some kind of indentation and variable naming rules. Otherwise it will be very hard to maintain.

Using array value with index as Variable Variable

The title may be a little confusing. This is my problem:
I know you can hold a variable name in another variable and then read the content of the first variable. This is what I mean:
$variable = "hello"
$variableholder = 'variable'
echo $$variableholder;
That would print: "hello". Now, I've got a problem with this:
$somearray = array("name"=>"hello");
$variableholder = "somearray['name']"; //or $variableholder = 'somearray[\'name\']';
echo $$variableholder;
That gives me a PHP error (it says $somearray['name'] is an undefined variable). Can you tell me if this is possible and I'm doing something wrong; or this if this is plain impossible, can you give me another solution to do something similar?
Thanks in advance.
For the moment, I could only think of something like this:
<?php
// literal are simple
$literal = "Hello";
$vv = "literal";
echo $$vv . "\n";
// prints "Hello"
// for containers it's not so simple anymore
$container = array("Hello" => "World");
$vv = "container";
$reniatnoc = $$vv;
echo $reniatnoc["Hello"] . "\n";
// prints "World"
?>
The problem here is that (quoting from php: access array value on the fly):
the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages.
Would PHP allow the subscript notation anywhere, one could write this more dense as
echo $$vv["Hello"]
Side note: I guess using variable variables isn't that sane to use in production.
How about this? (NOTE: variable variables are as bad as goto)
$variablename = 'array';
$key = 'index';
echo $$variablename[$key];

"Large multiple variable echo's" way to make simpler?

Say I am echoing a large amount of variables in PHP and I wont to make it simple how do i do this? Currently my code is as follows but it is very tedious work to write out all the different variable names.
echo $variable1;
echo $variable2;
echo $variable3;
echo $variable4;
echo $variable5;
You will notice the variable name is the same except for an incrementing number at the end. How would I write a script that prints echo $variable; so many times and adds an incrementing number at the end to save me writing out multiple variable names and just paste one script multiple times.?
Thanks, Stanni
You could use Variable variables:
for($x = 1; $x <= 5; $x++) {
print ${"variable".$x};
}
However, whatever it is you're doing there is almost certainly a better way: probably using Arrays.
I second Paolo Bergantino. If you can use an array that would be better. If you don't how to do that, here you go:
Instead of making variables like:
$var1='foo';
$var2='bar';
$var3='awesome';
... etc... you can make a singe variable called an array like this:
$my_array = array('foo','bar','awesome');
Just so you know, in an array, the first element is the 0th element (not the 1st). So, in order to echo out 'foo' and 'bar' you could do:
echo $my_array[0]; // echoes 'foo'
echo $my_array[1]; // echoes 'bar'
But, the real benefits of putting value in an array instead of a bunch of variables is that you can loop over the array like this:
foreach($my_array as $item) {
echo $item;
}
And that's it. So, no matter how many items you have in your array it will only take those three lines to print them out. Good luck you with learning PHP!
Use dynamic variable names:
for($i=1; $i < 6; $i++) echo ${'variable'.$i}

Categories