How to store an array into a session variable in php - php

//Returns 10 question from questions table
$result = mysqli_query($con,"SELECT question FROM questions ORDER BY rand() LIMIT 10' ");
while($row = mysqli_fetch_row($result))
{
$que[]=$row[0];
}
Now I need to store this whole set of $que[] in a session variable. (i.e 10 questions)
Something like this
$_SESSION['question'] = $que[];
$my_array[] = $_SESSION['question'];
so that $my_array[0] returns first question, $my_array[1] returns second questions and like that.
(Thanx for the help in advance)

Assign
$_SESSION['question'] = $que;
print_r($_SESSION['question'][0]); will give you first question.

You are almost correct, you only need the [] when adding to the array.
$_SESSION['question'] = $que;
Make sure that you have a session going first, placing this at the top of your script will start a session if one doesn't already exist:
if( !isset( $_SESSION ) ) {
session_start();
}
To pull it back up:
$array = $_SESSION['question']; //Assigns session var to $array
print_r($array); //Prints array - Cannot use echo with arrays
Final Addition
To iterate over the array, you can typically use for, or foreach. For statements really only work well when your array keys are incremental (0, 1, 2, 3, etc) without any gaps.
for( $x = 0, $max = count($array); $x < $max; ++$x ) {
echo $array[$x];
}
foreach( $array as &$value ) {
echo $value;
}
Both have been written in mind for performance. Very important to know that when using a reference (&$value, notice the &) that if you edit the reference, the original value changes. When you do not use by reference, it creates a copy of the value. So for example:
//Sample Array
$array = array( '0' => 5, '1' => 10 );
//By Reference
foreach( $array as &$value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Now equals array( '0' => 7, '1' => 12 )
//Normal Method
foreach( $array as $value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Still equals array( '0' => 5, '1' => 10 )
References are faster, but not if you are planing on modifying the values while keeping the original array intact.

use
session_start();
$_SESSION['question'] = $que;
&que = array(an array of your 10m question s);
when your want to call it on another page to get a line up of your questions, use
while (list($key, $value) = each($_SESSION)) {
#Echo the questions using $key
echo "Here is a list of your questions";
echo "<br/>";
while (list($key2, $value2) = each($_SESSION)) {
#$value2 show's name for the indicated ID
#$key2 refers to the ID
echo "<br/>";
echo "Question: ".$value2." ";
echo "<br/>";
}
echo "<br/>";
}
OR you can also use
print_r;

Related

I want to know the correct syntax of declaring multiple variables in php with small changes like mentioned below

$str='abcde';//for sub-question numbers
for ($i=1; $i <=10 ; $i++) {//i loop is for question numbers 1 to 10
for ($j=0; $j<5 ; $j++) {//j loop is for sub-questions from a to e
$q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
}
}
Here the main idea is to create 50 variables from q1a,q1b,... till q10d,q10e.
I'm not 100% clear on what the values of those variables will be, but here is how to create an array with those variable names in them.
$questions = array(1,2,3,4,5,6,7,8,9,10); //questions
$subQuestions = array('a','b','c','d','e'); //sub-question
$allQuestions = array();
foreach($questions as $question) {//loop the questions
foreach($subQuestions as $subQ) {//loop the sub questions
// I'm not clear what you're trying to do here -> $q{$i}{$str[$j]}=$_POST['q{$i}{$str[j]}'];//not sure about this part
$allQuestions["q" . $question . $subQ] = "I'm an empty value right now"; //what value goes here?
}
}
var_dump($allQuestions);
You can do something like this
$values = array("q1a", "q1b", "q1c", "q1d", "q1e", "q2a", "q2b", "q2c", "q2d", "q2e");
for($i=;$i<$sizeof($values);$i++)
{
$values[$i] = $_POST['q{$i}{$str[j]}'];
}
If all your POST vars which you want to grab are prepended with q then just filter them with array_filter().
Then you can use extract(), but tbh, you should just use the array.
<?php
$_POST = [
'q1' => 'baz',
'foo' => 'bar',
];
$q = array_filter($_POST, function($k) {
return substr($k, 0, 1) === 'q';
}, ARRAY_FILTER_USE_KEY);
extract($q);
// filtered array
print_r($q);
// extract'ed
echo $q1;
Result:
Array
(
[q1] => baz
)
baz
https://3v4l.org/rvMR6

Effective way to get array index and value names

I have a 0 indexed array that I can't do much about, but inside this array there are values that I need to echo. example array is:
$x = array(0 => array('store'=> 107));
I would like to have 2 variables that both echo texts store and 107
I could do this, using
$var1 = array_keys($x[0]);
$var2 = array_values($x[0]);
echo $var1[0]; // store
echo $var2[0]; // 107
I would like to know if there is a more effective way of getting those values, or remving that first 0 index. as array_filter($x) or unset($x) obviously don't work as in other cases.
As an alternative, you could also use combinations of key() and reset() if you're curious.
$x = array(0 => array('store'=> 107));
$y = reset($x); // point to first element
$key = key($y); // get the current key, store
$val = reset($y); // get the value
echo $key; // store
echo $val; // 107
this should work for you.
$x = array(0 => array('store'=> 107));
foreach($x as $y){
foreach ($y as $key => $value){
echo $key;
echo $value;
}
}

How to access php variable using concatenation [duplicate]

This question already has answers here:
PHP - Variable inside variable?
(6 answers)
Closed 8 years ago.
I want to access a variable that is either called $item1, $item2 or $item3.
I want to access this variable inside a for loop where $i is ++ every time. using $item.$i or something similar. However using that code means that I am trying to join the contents of two variables, and there is no variable called $item.
Arrays: A Better Method
While PHP does permit you to build dynamic variable names from various other values, you probably shouldn't in this case. It seems to me that an array would be more appropriate for you:
$items = array( 0, 12, 34 );
You could then access each value individually:
echo $items[0]; // 0
echo $items[1]; // 12
Or loop over the entire set:
foreach ( $items as $number ) {
echo $number; // 1st: 0, 2nd: 12, 3rd: 34
}
Merging Multiple Arrays
You indicated in the comments on the OP that $item1 through $item3 are already arrays. You could merge them all together into one array if you like with array_merge(), demonstrated below:
$item1 = array( 1, 2 );
$item2 = array( 3, 4 );
$item3 = array( 5, 6 );
$newAr = array_merge( $item1, $item2, $item3 );
print_r( $newAr );
Which outputs:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
If You Must: Dynamic Variable Names
For completeness, if you were to solve your problem by dynamically constructing variable names, you could do the following:
$item1 = 12;
$item2 = 23;
$item3 = 42;
for ( $i = 1; $i <= 3; $i++ ) {
echo ${"item".$i} . PHP_EOL;
}
build the variable name you want to access into another variable then use the variable variable syntax
<?php
$item1 = 'a';
$item2 = 'b';
$item3 = 'c';
for ($i = 1; $i<=3; $i++) {
$varname = 'item' . $i;
echo $$varname;
}
?>
output:
abc
Note there are other ways to do this, see the manual.
Use ${'item'.$i}
If $i == 1, then you will access $item1.
But it's better to use arrays in your case.
for ($i =1;$i<4;$i++){
$var = 'item'.$i;
echo $$var;
}
Here you are using the the double $ to create a variable variable.
Can you use an array instead of individual variables? then you can reference array elements by index value based in i.
$items = array();
$i = 1;
$items[$i] = "foo";
$i++;
$items[$i] = "bah";
echo $items[1], $items[2]; // gives "foobah"
It's a little late, and the accepted answer is the proper way to do this, but PHP does allow you to access variable variable names in the way OP describes:
<?php
$item1 = 'a';
$item2 = 'b';
$item3 = 'c';
for($i=1;$i<=3;$i++)
echo ${"item$i"}; //Outputs: abc
?>

multi dimension array split with explode PHP

i have multidimension array
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
then i explode $a
$array_a = explode("|", $a);
//loop
for($i=0;$i<=count($arr_a)-1;$i++){
arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
echo $id." have access ".$access;
}
}
//result
0 have access 5
1 have access add
0 have access 4
1 have access edit
0 have access 6
1 have access add
0 have access 6
1 have access edit
0 have access 19
1 have access add
0 have access 19
1 have access delete
0 have access 19
1 have access view
//-end result
the problem is :
how i can make the result like this
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
I think Regex would be a better solution in this case, in case you haven't considered using it.
Sample (Tested):
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$result = array();
// match each pair in the input
if (preg_match_all('/(\\d+)\\,(.*?)(\\||$)/m', $a, $matches)){
foreach( $matches[1] as $match_index => $match ){
$result[$match][] = $matches[2][$match_index];
}
}
// loop through the results and print in desired format
foreach( $result as $entry_index => $entry ){
echo "$entry_index have access " . implode( ',', $entry ) . "\n";
}
output:
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
Using regex simplifies the code and also makes it somewhat easier to change the format of the input that is supported.
The $result array ended up with a hash map using your numeric ids as the keys and arrays of permissions (add, delete, etc) as the value for each key.
Try this one (tested):
// intial data
$strAccess = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
// build access array
$arrayAccess = array();
$tmpList = explode('|', $strAccess);
foreach($tmpList as $access)
{
list($idUser, $right) = explode(',', $access);
if (!isset($arrayAccess[$idUser]))
$arrayAccess[$idUser] = array();
$arrayAccess[$idUser][] = $right;
}
// print it out
foreach($arrayAccess as $idUser => $accessList)
echo $idUser." has access ".implode(",", $accessList)."\n";
You can use counter something like
$count5=0;
foreach($arr_b as $id => $access){
if($access=='5'){
$count5++;
}
echo $id." have access ".$count5;
}
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$array_a = explode("|". $a);
//loop
$aRights = array();
for($i=0;$i<=count($arr_a)-1;$i++){ $arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
$aRights[$id][] = $access;
}
}
foreach( $aRights as $id=>$rightsList){
echo $id." have access ";
$i=1;
foreach($rightsList as $r){
echo $r;
if($i != count($rightsList)) echo ",";
$i++;
}
}
What about something like hashmapping:
$tobegenerated = array();
$a = explode(yourdelimiter,yourstring);
foreach ($a as $cur)
{
$b = explode(delimiter,$cur);
$tobegenerated[$cur[0]] = $cur[1];
}
//Print hashmap $tobegenerated
This should work, remember that in php arrays are also hash maps
Edit 1:
Arrays in PHP are hash maps. A hash map can be interpreted as an array where keys can be anything and value can be anything too. In this case, you would like to use a hash map because you need to bind values that are "outside" the range of the array (even if they are ints). So a hash map is exactly what you want, allowing to specify anything as a key.
How a hash map work is something that you can search on google or on wikipedia. How arrays work in php can be found here

Cleanest way of working out next variable name based on sequential order?

Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}

Categories