Can I use array_push on a SESSION array in php? - 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

Related

Iterating through a $_session array

I have created a session array as follows
$_SESSION['memberInfo']['memberFirstName'] = ($first_name);
$_SESSION['memberInfo']['memberLastName'] = ($surname);
$_SESSION['memberInfo']['hash'] = ($hash);
$_SESSION['memberInfo']['templateSrc'] = ($newTemplateSrc);
in other pages where I'm trying to get the values from the array I have tried foreach and while loops without success, I can see the array in a var_dump
var_dump($_SESSION['memberInfo']);
which shows in console as
array(4) {
["memberFirstName"]=>
string(8) "Geoffrey"
["memberLastName"]=>
string(6) "Turner"
["hash"]=>
string(60) "$2y$10$YBE1tc.BK7yq6bBr/JAlWuN0H8xGdoNSAWzU4/zfd1r3v7jprNBD2"
["templateSrc"]=>
string(61) "../userDirectory/558386500/html/Geoffrey_Turner_558386500.php"
}
in the pages where im trying to itterate the array I have tried using
foreach ($_SESSION['memberInfo'] as $name)
{
$first_name = $name['memberFirstName'];
}
the responce I get shows as
Warning: Illegal string offset 'memberFirstName'
which I believe suggests the itteration is reading an empty array
I can echo out the array using
foreach ($_SESSION['memberInfo'] as $key => $val) {
echo "$key = $val\n";
}
which results in
memberFirstName = Geoffrey
memberLastName = Turner
hash = $2y$10$YBE1tc.BK7yq6bBr/JAlWuN0H8xGdoNSAWzU4/zfd1r3v7jprNBD2
templateSrc = ../userDirectory/558386500/html/Geoffrey_Turner_558386500.php
but for the life of me I cannot seem to figure out how to get each of the array values individually and assign them to a variable
Your foreach makes no sense as you looping an trying to assing single variable too many times for no benefits. So this to be removed:
foreach ($_SESSION['memberInfo'] as $name =) {
$first_name = $name['memberFirstName'];
}
as all you need is:
$first_name = $_SESSION['memberInfo']['memberFirstName'];
how to get each of the array values individually and assign them to a variable
You can use extract which extracts each value and assigns it to a variable.
extract($_SESSION['memberInfo']) this should create the following variables
$memberFirstName, $memberLastName, $hash, $templateSrc
Here is a demo http://ideone.com/XYpC7n

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);
}

creating variable names from an array list

How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php

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.

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories