Storing Variable Names in an Array - php

So I have a List of Variables
$TestData1="Hello";
$TestData2="";
$TestData3="0";
$TestData4="Yes";
$TestData5=" ";
$TestData6="No";
I want to make a function that will run all these variables through a filter. I want to make this a loop that checks all the variables in one shot. I had the idea of storing the variable names in an array. This is shown below.
$TestArray=array("TestData1", "TestData2", "TestData3", "TestData4","TestData5","TestData6");
So my main question is how would I take these names in the array and run a loop that checks to see if a certain condition is met. Example below.
foreach ($TestArray as $Data):
$VariableToTestConnditions="$".$Data;
endforeach;
I know that statement doesn't work, but it is all I could think of. The out come of this would be if the variable value =="Yes" then is would change the original variable's value to "N/A". So after it checks all the variables, it would change $TestData4 to "N/A".

instead of having an array of the names, it would make more sense to have an associative array (key value pairs):
$TestArray = array(
"TestData1" => "Hello",
"TestData2" => "",
"TestData3" => "0",
"TestData4" => "Yes",
"TestData5" => " ",
"TestData6" => "No"
);
now if you wanted to test a variable:
foreach($TestArray as $key => $value) {
if($VariableToTestConnditions == $value) {
//do something
}
}
if you wanted to change the value of a testdata:
$TestArray["TestData1"] = "Good Bye";
this way is much neater and simpler.

i used echo to demo the syntax, you can use what you like
$TestData1="Hello";
$TestData2="";
$TestData3="0";
$TestData4="Yes";
$TestData5=" ";
$TestData6="No";
$TestArray=array("TestData1", "TestData2", "TestData3", "TestData4","TestData5","TestData6");
foreach($TestArray as $a){
echo ${$a};
//or
echo $$a;
}

Use the two-dollar sign.
See PHP variable variables: http://php.net/manual/en/language.variables.variable.php
foreach ($TestArray as $Data):
$VariableToTestConnditions=$$Data;
endforeach;

Related

key and value array access in php

I am calling a function like:
get(array('id_person' => $person, 'ot' => $ot ));
In function How can I access the key and value as they are variable?
function get($where=array()) {
echo where[0];
echo where[1];
}
How to extract 'id_person' => $person, 'ot' => $ot without using foreach as I know how many key-values pairs I have inside function?
You can access them via $where['id_person'] / $where['ot'] if you know that they will always have these keys.
If you want to access the first and second element, you can do it like this
reset($where)
$first = current($where);
$second = next($where);
Couple ways. If you know what keys to expect, you can directly address $where['id_person']; Or you can extract them as local variables:
function get($where=array()) {
extract($where);
echo $id_person;
}
If you don't know what to expect, just loop through them:
foreach($where AS $key => $value) {
echo "I found $key which is $value!";
}
Just do $where['id_person'] and $where['ot'] like you do in JavaScript.
If you do not care about keys and want to use array as ordered array you can shift it.
function get($where=array()) {
$value1 = array_shift($where);
$value2 = array_shift($where);
}

Can I use array_push on a SESSION array in php?

I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.
This is the session:
$_SESSION['names']
I want to add a series of names to that array using array_push like this:
array_push($_SESSION['names'],$name);
I am getting this error:
array_push() [function.array-push]:
First argument should be an array
Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?
Yes, you can. But First argument should be an array.
So, you must do it this way
$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);
Personally I never use array_push as I see no sense in this function. And I just use
$_SESSION['names'][] = $name;
Try with
if (!isset($_SESSION['names'])) {
$_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
$_SESSION['total_elements']=array();
array_push($_SESSION['total_elements'], $_POST["username"]);
Yes! you can use array_push push to a session array and there are ways you can access them as per your requirement.
Basics:
array_push takes first two parameters array_push($your_array, 'VALUE_TO_INSERT');.
See: php manual for reference.
Example:
So first of all your session variable should be an array like:
$arr = array(
's_var1' => 'var1_value',
's_var2' => 'var2_value'); // dummy array
$_SESSION['step1'] = $arr; // session var "step1" now stores array value
Now you can use a foreach loop on $_SESSION['step1']
foreach($_SESSION['step1'] as $key=>$value) {
// code here
}
The benefit of this code is you can access any array value using the key name for eg:
echo $_SESSION[step1]['s_var1'] // output: var1_value
NOTE: You can also use indexed array for looping like
$arr = array('var1_value', 'var1_value', ....);
BONUS:
Suppose you are redirected to a different page
You can also insert a session variable in the same array you created. See;
// dummy variables names and values
$_SESSION['step2'] = array(
's_var3' => 'page2_var1_value',
's_var4' => 'page2_var2_value');
$_SESSION['step1step2'] = array_merge($_SESSION['step1'], $_SESSION['step2']);
// print the newly created array
echo "<pre>"; // for formatting printed array
var_dump($_SESSION['step1step2']);
echo "<pre>";
OUTPUT:
// values are as per my inputs [use for reference only]
array(4) {
["s_var1"]=>
string(7) "Testing"
["s_var2"]=>
int(4) "2124"
["s_var3"]=>
int(4) "2421"
["s_var4"]=>
string(4) "test"
}
*you can use foreach loop here as above OR get a single session var from the array of session variables.
eg:
echo $_SESSION[step1step2]['s_var1'];
OUTPUT:
Testing
Hope this helps!
Try this, it's going to work :
session_start();
if(!isset($_POST["submit"]))
{
$_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}
if(isset($_POST["submit"]))
{
$aa = $_POST['text1'];
array_push($_SESSION["abc"], $aa);
foreach($_SESSION["abc"] as $key => $val)
{
echo $val;
}
}
<?php
session_start();
$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');
array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);
foreach ($_SESSION['data'] as $eacharray)
{
while (list(, $value) = each ($eacharray))
{
echo "Value: $value<br>\n";
}
}
?>
output
Value: pappu Value: 10 Value: tippu Value: 12

How to access a $_POST item through the following array kind of syntax?

If i send four POST variables, but the second one — I dont know that the name="" tag will be; how can I access it? Can i use $_POST[1] or not?
Here's one solution using internal pointers:
if(count($_POST) > 1){ // just a check here.
reset($_POST); // reset the pointer regardless of its position
$second_value = next($_POST); // get the next value, aka 2nd element.
}
By the way with regards to the numeric index: PHP $_POST and $_GET are associative arrays! They do not support something like $_POST[0] or $_POST[1]. They will return NULL because they are not set. Instead $_POST["name"] would work.
From the PHP Manual: "An associative array of variables passed to the current script via the HTTP POST (or GET) method."
i have a handy function for this
function nth($ary, $n) {
$b = array_slice($ary, intval($n), 1);
return count($b) ? reset($b) : null;
}
in your case
$foo = nth($_POST, 1);
foreach( $_POST as $key => $value ){
if( is_int($key) ) //do something with $value
}
This will work if you know the other $_POST values have names in your forms (i.e., keys that aren't numbers).
You can loop through it:
foreach ($_POST as $k => $v) {
if (substr($k, 0, 3) == 'id_') {
// do stuff
}
}
But it really depends on what the criteria for the search is. In the above example it's pulling all the POST variables that start with "id_". You may be able to do it simpler if you have a different/better criteria.
You can if you convert it using array_values() first.
Example
<?php
$a = array(
"first key" => "first value",
"second key" => "second value",
);
$v = array_values($a);
echo "First value: {$v[0]}\n";
?>
Output
$ php -f a.php
First value: first value
EDIT: Thanks for commentators pointing out the initial error.
use
<?php
print_r($_POST);
?>
this will give you an idea of what is the key of the field you don't know.
Make a copy :
$vars = $_POST;
Remove the names you know :
unset( $vars[ "known variable 1" ] );
unset( $vars[ "known variable 2" ] );
All that remains is the variables you need : extract them with array_values or enumerate them with foreach, whatever.
a simple for each will do the trick if you do not know the array keys on the $_POST array
foreach($_POST as $key=>$value):
print 'key'.$key.' value'.$value
endforeach;
But it is recommended to know what your post variables are if you are planning on processing them.

What does "=>" mean in PHP?

What does the => operator mean in the following code?
foreach ($user_list as $user => $pass)
The code is a comment at PHP.net.
The user does not specify the value of $user_list, $user or $pass.
I normally see that => means equal or greater than.
However, I am not sure about its purpose here because it is not assigned.
I read the code as
process a list of users in integers
such that the value of each user is equal or greater than password
The above does not make sense to me.
=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass.
Example:
$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
Note that this can be used for numerically indexed arrays too.
Example:
$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
It means assign the key to $user and the variable to $pass
When you assign an array, you do it like this
$array = array("key" => "value");
It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.
According to the PHP Manual, the '=>' created key/value pairs.
Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.
And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:
$array = array("test" => "foo");
foreach($array as $key => $value)
{
echo $key . " : " . $value; // Echoes "test : foo"
}
foreach($array as $value)
{
echo $value; // Echoes "foo"
}
Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.
You might want to take a look at the documentations of, at least:
foreach
arrays
Here, you are having an array, called $user_list, and you will iterate over it, getting, for each line, the key of the line in $user, and the corresponding value in $pass.
For instance, this code:
$user_list = array(
'user1' => 'password1',
'user2' => 'password2',
);
foreach ($user_list as $user => $pass)
{
var_dump("user = $user and password = $pass");
}
Will get you this output:
string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)
(I'm using var_dump to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo)
"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...
As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!
An array in PHP is a map of keys to values:
$array = array();
$array["yellow"] = 3;
$array["green"] = 4;
If you want to do something with each key-value-pair in your array, you can use the foreach control structure:
foreach ($array as $key => $value)
The $array variable is the array you will be using. The $key and $value variables will contain a key-value-pair in every iteration of the foreach loop. In this example, they will first contain "yellow" and 3, then "green" and 4.
You can use an alternative notation if you don't care about the keys:
foreach ($array as $value)
Arrays in PHP are associative arrays (otherwise known as dictionaries or hashes) by default. If you don't explicitly assign a key to a value, the interpreter will silently do that for you. So, the expression you've got up there iterates through $user_list, making the key available as $user and the value available as $pass as local variables in the body of the foreach.
$user_list is an array of data which when looped through can be split into it's name and value.
In this case it's name is $user and it's value is $pass.

How do I output these PHP array values?

Using PHP, how do I output/display the values from this array within my web page:
http://api.getclicky.com/api/stats/4?site_id=83367&sitekey=e09c6cb0d51d298c&type=clicks&output=php&unserialize
Looks like a print_r() output to me.
Use a foreach statement to iterate over the array echoing each as you go
foreach($data as $k => $v) {
echo "{$k} => {$v}";
}
$data is the input data
$k is the key $v is the $value
The above is only useful for a single depth array for an array of arrays like the example data provided you need to use a recursive function then check to see if the value is an array if so call the function recursivally.
If the data structure never changes then some nested loops will do the job. (some people think recursion is evil, I pity them)
DC
Start with our Array
$myarray = array(
"Key1" => "This is the value for Key1",
"Key2" => "And this is the value for Key2"
);
Show All Output (Helpful for Debugging)
print_r($myarray);
/* or */
var_dump($myarray);
Show only a Single Value
print $myarray["Key1"]; // Prints 'This is the value for Key1'
print $myarray[0]; // Prints 'This is the value for Key1'

Categories