I'm learning php on a very basic level and need som assistance.
I want to echo variables from one file to another. I'll try to reproduce:
folder/file1.php
file1.php contains 3 different php scripts:
php $var1 = "Hello"
php $var2 = "Goodbye"
php $var3 = "Nice"
And i want to echo one of the three variables randomly (scrambled) on various pages.
I use this now:
php include 'folder/file1.php'; echo get_($var1);
But it only displays the $var1 text.
How about:
<?php
$var1 = "Hello";
$var2 = "Goodbye";
$var3 = "Nice";
$i = rand(1, 3);
echo ${"var" . $i}
?>
At run time ${"var" . $i} is calculated to be $var1, $var2 or $var3.
Using php rand and dynamically created variable will let you do it. You can just continue to include your other files above this script and ensure the variables are named in a static way as shown above and it will work.
Example: Here (click edit then ideoneit)
put those vars in an array, and randomly select an element from the array:
$myItems = array("hello","goodbye","lovely");
echo $myItems[rand(0,2)];
http://us2.php.net/rand
Related
I have a file, let's call it first.php. It echoes a lot of text. Inside that text I also want to include something another file, second.php echoes. I'd like to do this without including the code from second.php, because there are collisions.
TL;DR I want a PHP script to execute another one, wait for it to print, and then echo whatever it printed.
Tried
echo something
include second script
echo something else
But it doesn't work because of said collisions. The second script only prints a short plain text.
Better example
a.php prints "hello" and "world" and declares $i=1
b.php prints "beautiful" and declares $i=2
I want to print "hello beautiful world" and have $i=1
You could run the second script through the CLI with shell_exec
echo something
shell_exec("php second.php");
echo something else
However, this won't work if the second script needs to access variables that are set by the webserver, like $_GET or $_SERVER. If you need to pass certain variables along, you can send them as command line arguments. But the second script will then have to access them using $argv, not $_GET.
shell_exec("php second.php " . escapeshellarg($_GET['id']));
second.php can get the ID from $argv[1].
Imo you should really solve the actual problem by not re-using variables which are sharing scope. If you cannot do that it means you are putting too much in the current scope. However if you really want to do it you could wrap it in a function (which has its own scope).
<?php
$i = 1;
echo 'hello';
echo call_user_func(function() {
// in your case this would be a include statement
$i = 2;
return 'beautiful';
});
echo 'world';
var_dump($i); // 1
If you actually need to "import" variables from the current scope create a closure instead:
<?php
$i = 1;
echo 'hello';
echo call_user_func(function() use ($theVariable) {
// in your case this would be a include statement
$i = 2;
return 'beautiful';
});
echo 'world';
var_dump($i); // 1
You could include the second file in a function. Functions have their own variable scopes. So, variables of the second file can not overwrite variables with the same name of the first script file.
$myvar = 1;
include 'first.php';
callSecond ();
echo $myvar;
function callSecond () {
include 'second.php';
}
echo $myvar would give 1, even when 'second.php' assigns $myvar = 2;
I want to flood some random data in a PHP form. Can I do it?
I want to actually test my website and database ofcourse. All I want to know that is it capable of handling if multiple registration is done at same time.
cURL is a very good tool to fill up a (POST) form a submit it. You may find a cURL library implementation in PHP, so you can use a "familiar" language to get random data, but you can also use the command line version.
First, create pages that echo data from source.
data1.php
data2.php
data3.php
data4.php
Second create a php page that will do the following:
Create variables from data sources.
Pass variables into array.
Randomly select a specific variable.
Echo results into page.
// variables from data
$var1 = file_get_contents('data1.php');
$var2 = file_get_contents('data2.php');
$var3 = file_get_contents('data3.php');
$var4 = file_get_contents('data4.php');
// pass variables into array
$data = array($var1, $var2, $var3, $var4,);
$dkey = array_rand($data); // random selection
echo 'Data: '.$data[$dkey]; // echo selection
Your finished code will look like this:
<?php
$var1 = file_get_contents('data1.php');
$var2 = file_get_contents('data2.php');
$var3 = file_get_contents('data3.php');
$var4 = file_get_contents('data4.php');
$arr = array($var1, $var2, $var3, $var4,);
$key = array_rand($arr);
echo 'Data: '.$arr[$key];
?>
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']);
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];
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}