How to add value to associative array that store in session? - php

include('session.php');
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$wishlist = array("$productname" => $productcode);
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);
This code set as an array to a session named "wishlist".
The problem is that the session is being replaced. I want to add to the array if it already exists.
So how can I update my array with new data.
I have tried the following.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
/*
How Can I Update array ???
*/
}
The array output is like so. It is associated not numeric indexed.
And i want result in single array. Not array in array.
[mobile] => iphone_2
Thank you.

In short, you can do this (if I understand the question correctly):
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
array_push($wishlist, array("$productname" => $productcode));
}
array_push is a function that will add information to the end of an array. In this instance, we are using it to add the product array to the current wishlist.
An alternative simple solution would be:
// create a blank array if the session variable is not created
// array_push requires an array to be passed as the first parameter
$wishlist = isset($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : array();
//$wishlist = $_SESSION["wishlist"] ?? array(); // this is for PHP 7+
array_push($wishlist, array("$productname" => $productcode));
// you can then access each product as:
$wishlist["mobile"];
Or replace line 5 from the above code snippet with the following:
$wishlist[$productname] = $productcode;
This would save you from creating an empty array as in line 3.
The advantage that array_push has over this is that you can add multiple products at once such as:
$products = [$productname1 => $productcode1, $productname2 => $productcode2];
array_push($wishlist, $products);
The one thing I have noticed is that you are setting the session to $lastsession as well as using $wishlist. Try and keep duplicate variables to non-existent.

$_SESSION["wishlist"] = array( 'product1' => 'product1 Name' );
// Initial products in session
$temp_session = $_SESSION["wishlist"];
//store products in wishlist in temp variable
$temp_session['mobile'] = 'iphone_2';
// Add new product to temp variable
$_SESSION["wishlist"] = $temp_session;
//Update session
print_r( $_SESSION["wishlist"] );

Set the wishlist data from the session to variable and then just add the new product to this variable. After that update the wishlist data in the session.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
// do the same as: $wishlist = !empty($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : [];
$wishlist = $_SESSION["wishlist"] ?? [];
$wishlist[$productname] = $productcode;
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);

Related

Loop through list of form elements array to get or fetch the elements we need or want to keep

This is my current code, I'm looking for a more efficient way of writing it.
Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.
$formValues = $form_state->getValues();
$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];
tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
Seeing as you know the keys you'd like to keep you can do the following:
<?php
/** The keys you want to keep... **/
$keys_to_keep = [
];
/** Will be used to store values for saving to $_SESSION. **/
$temp_array = [];
/** Loop through the keys/values. **/
foreach ($formValues as $key => $value) {
/** The correct key i.e. the key you'd like to save. **/
if (in_array($key, $keys_to_keep)) {
/** What you wish to do... **/
$temp_array[$key] = $value;
}
}
$_SESSION['sessionName']['formName'] = $temp_array;
?>
What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.
Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.
Reading Material
foreach
in_array
You can use variable variables and a foreach.
Foreach($formValues as $key => $var){
$$key = $var;
}
Echo $relocation ."\n" . $europe;
https://3v4l.org/QeLjp
Edit I see now that your array variable keys are not always the same as the variable name you want.
In that case you can't use the method above.
In that case you need to use list() = array.
List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.

PHP POST data assign to two dimensional array

I have a add-to-cart form to $_POST all data, and needed to store into a two dimensional array and assign to a session:
for example print_r($_POST) is:
Array("prod"=>"ZIU%3D","price"=>"68.00","alt-variation-1"=>"Red","alt-variation-2"=>"L","qty"=>"1")
to loop each $_POST:
foreach($_POST as $field => $value){
$f[] = $field;
$v[] = $value;
}
I looking for a way to assign above $f and $v into an array such as:
$new_product = array(array($f => $v));
and store in a session like:
$_SESSION['products'] = $new_product;
or any alternate way instead?
$_SESSION['products'][] = $_POST; would append the entire post array to the session products array, but you need to validate the data posted by the user.
A better way would be:
$data = $_POST;
// sanitise and validate $data here
$_SESSION['products'][] = $data;
An example for #HamzaZafeer:
foreach($_SESSION['products'] as $product){
echo $product['price'];
}
you can encode your array to JSON and store it in a session with:
$myJson = json_encode($_POST);
$_SESSION['myJson'] = serialize($myJson);

PHP Array into array - error

I'm trying to add an array into an other array at a specific key. But I have this message :
array_push() expects parameter 1 to be array, null given
I don't understand because in the else I create the array.
$key = $this->input->get('vente');
if(array_key_exists($key,$this->session->userdata('panier'))){
array_push($this->session->userdata('panier')[$key],$toAdd);
}else{
$this->session->userdata('panier')[$key] = array();
array_push($this->session->userdata('panier')[$key],$toAdd);
}
$this->session->userdata return an array but you can't modify it directly. Try this :
<?php
// Storing the session item in a var
$panier = $this->session->userdata('panier');
// $this->session->userdata return null when the item doesn't exist, so we have to check it
if (empty($panier)) $panier = array();
$key = $this->input->get('vente');
if( array_key_exists($key, $panier) ) {
array_push($panier[$key], $toAdd);
} else {
$this->session->userdata('panier')[$key] = array();
array_push($panier[$key], $toAdd);
}
// Then, we set the var in session again !
$this->session->set_userdata('panier', $panier);
Don't hesitate if you need more explanations.

Assoc. Array, get Element with special id

I have the assoc array alldept.
I want now the 'name' element from the array with the id e.g. '1';
How do I access the id and output the 'name'?
The id is saved in $result[$i]['abteilung']
Thank you very much!
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt){
$alldept[] = array("id" => $singledpt->getId(),
"name" => $singledpt->getName()
);
}
As you are building this array yourself it would seem sensible to build it in a way that is later usable.
So why not build the array like this
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt) {
$alldept[ $singledpt->getId() ] = $singledpt->getName();
}
Now if you know you want the name of dept = 1 you just do
echo $alldept[1];
What I would suggest is to keep id as key and name as value:
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt){
$alldept[$singledpt->getId()] = $singledpt->getName();
}
Note: I am assuming getId will be unique
Then to fetch name, you can simply type $alldept[$id].
This might not be an answer, just an alternative. You can avoid a loop.

Adding item as array in session array in php

I am working on a shopping cart project, and I am adding some items in session as array but when I add one item, then it is displaying two items, code is as below :-
if(!empty($_GET['pid'])) {
if(!empty($_SESSION['cart'])) {
$item = array($_GET['id'], $_GET['pid'], $_GET['item_weight'], $_GET['item_quantity'], $_GET['per_item_price'], $_GET['total_price'], $_GET['savings'], $_GET['product_name'], $_GET['type']);
$index = count($_SESSION['cart']);
$_SESSION['cart'][$index] = $item;
} else {
$item = array($_GET['id'], $_GET['pid'], $_GET['item_weight'], $_GET['item_quantity'], $_GET['per_item_price'], $_GET['total_price'], $_GET['savings'], $_GET['product_name'], $_GET['type']);
$_SESSION['cart'] = array($item);
}
}
Any idea what's wrong with my code?
you can do this much more simply using [] to push items to your array:
$_SESSION['cart'][] = array(
'some' => 'stuff'
);
But your problem is you have used array 2 times .. because $item is already in the form of array.. again your are trying to store array to $_SESSION['cart']
$item = array($_GET['id'], $_GET['pid'], $_GET['item_weight'], $_GET['item_quantity'], $_GET['per_item_price'], $_GET['total_price'], $_GET['savings'], $_GET['product_name'], $_GET['type']);
//$_SESSION['cart'] = array($item);
$_SESSION['cart'] = $item;

Categories