Can we do like this using PHP SESSION array? - php

Hi can we create two dimensional array using php session. If possible how to unset values randomly.

No, PHP does not implement multi-dimensional arrays. However an element of an array can be an array itself. And any PHP data item can be stored in the session (however resources become meaningless outisde the thread they were initialized in, and objects require class definitions to be referenced from the session).
e.g.
<?php
$two_d=array(
array(1,2,3),
array(4,5,6),
array(7,8,9),
array('#','.','=')
);
$two_d[3][2]='*'; // was '='
how to unset values randomly
This would be an oxymoron in a 2-dimensional array. But is perfectly valid in the context of an array of arrays:
unset($two_d[1]); // removed the whole second row from the above
unset($two_d[0][1]); // $two_d[0] is now array(1,3)

$_SESSION['whateverValue'] = Array(
1 => Array (
'a','b','c','d'
),
2 => Array (
'q','w','e','r','t'
)
);
Voila, a two-dimensional array, in a session.
The session variables are in no way special while the script is executing. Their only "magic" is that they are unserialized at session_start() and serialized at session_close()

Related

Referencing an associative array added as value inside another associative array

I have the following structure:
$positions = array();
$salaries = array();
$registers = ['Position' => $positions, 'Salary' => $salaries];
Since I created the positions and salaries associative arrays at the beginning using the array() syntax I assumed that later in the code I can just write:
$salaries += [$name => $salary];
But found out that at the end when tried to get some data using the registers array:
$registers['Position'] or $registers['Salary'] after I've done some filtering everything was empty and I had to reference it via registers to actually put data in:
$registers['Salary'] += [$name => $salary];
or create the registers array later in the code near the end of the script when the other arrays - positions and salaries were already full with the needed data.
My question is - since I put positions and salaries as values inside registers array does that mean I lose the ability to reference them as separate / independent arrays. I created them as described with that purpose in mind and registers array is for filtering purposes and I made it at the beginning so I have all that code at the very top of the script.
Will be very grateful for any info on the matter.

PHP Specific Array Organization Function

I have a few session arrays which I happen to be removing specific indexes from. For example, I have a session named $_SESSION['products'], this session has these elements: $_SESSION['products'][0], $_SESSION['products'][1], and $_SESSION['products'][2].
I am trying to remove any one of those variables, the problem is when you remove the second variable, you mess up the array so that it cannot be displayed in a for loop. Is there a way to rearrange the following: $_SESSION['products'][0] and $_SESSION['products'][2] to $_SESSION['products'][0] and $_SESSION['products'][1] with a PHP built-in function? If not, is it even possible?
You can achieve this with array_values like:
unset($_SESSION['products'][2]); // assuming the product key
// exist in product array sess
$_SESSION['products'] = array_values($_SESSION['products']);
Manual
array_values() returns all the values from the array and **indexes the array numerically.**

What does "*RECURSION*" mean when printing $GLOBALS?

When I print $GLOBALS using this code:
<?php print_r($GLOBALS); ?>
I get this output:
Array ( [_GET] => Array ( ) [_POST] => Array ( ) [_COOKIE] => Array ( ) [_FILES] => Array ( ) [GLOBALS] => Array *RECURSION* )
What does "*RECURSION*" mean in this case, and why are $_SERVER, $_REQUEST, etc. not printed as well?
See this part of PHP Manual:
Keep in mind that $GLOBALS is, itself, a global variable. So code like this won't work:
<?php
print '$GLOBALS = ' . var_export($GLOBALS, true) . "\n";
?>
This results in the error message: "Nesting level too deep - recursive dependency?"
You already have retrieved the whole list - you just cannot display part of it (the one containing a recursion, because you would have timeout rather than anything meaningful).
When it comes to $_REQUEST, it is a derivative from $_GET, $_POST and $_COOKIE, so its content is redundant.
EDIT: There is an old bug / feature, that seems to be populating $GLOBALS with $_SERVER and $_REQUEST when they are accessed. So try to access $_REQUEST and hope it helps. Anyway, it can be found in $GLOBALS after that: ideone.com/CGetH
$GLOBALS contains itself as an array. In the PHP reference you can find the definition of $GLOBALS:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
Therefore, it has to contain also itself, which leads to a recursion.
The other arrays are probably just empty, since nothing else has happened in your script.
There is an old joke about recursion: "To understand recursion, you must understand recursion".
BTW: It outputs _SERVER on my computer.

two dimension session issue with codeigniter

I want to store two dimensional array in session, where i keep creating the array through a function call.
I am trying with this code
function nextQuestion($questionId,$response)
{
$this->session->set_userdata("res[$questionId][]"),$response);
}
but this is not creating a two dimensional array
The key stored in the session must be a string but the value can be a multi dimensional array.
You can retrieve the array, manipulate it and save it in the session again like this:
$session_response = $this->session->userdata("res");
//some manipulation on $session_response
$this->session->set_userdata('res', $session_response);
sametimes codeigniter session library can be boring.
if i add array to session, i serialize the array.
You can serialize array and get back with unserialize. or you can use php session library.

do array() destroy all previous values?

I have an $array with some values stored on it. Now, if I do :
$array=array();
all values/index are deleted? Or I need to use unset() before it?
A new array is being created with array() and this new array object is assigned to the variable $array.
The variable ($array) no longer points to the original array object -- and because PHP is a garbage collected language -- the original array object will be eligible for reclamation if (and only if) it is no longer strongly reachable from a root object. (The actual time the previous array object and objects it contained are actually deleted depends on other factors.)
Happy coding.
See PHP Garbage Collection Manual for more details -- PHP uses a hybrid GC (ref-count and cycle-breaking).
Yes the reassignment just wipes out all the data from the array. But to get clear understanding of the garbage collection please check the PHP Reference Counting Basics.
$array = array('apples', 'oranges', 'bananas');
print_r($array);
//Array ( [0] => apples [1] => oranges [2] => bananas )
$array = array();
print_r($array);
//Array ( )
Your intent would be clearer if you used something like
$array = null;
(and even clearer if you used a better name than $array!)

Categories