Store array of objects in PHP session - php

How can I store/remove/get an array of objects in the PHP session?
I tried this for adding:
array_push($_SESSION['cart'], serialize($item));
and this for removing:
function removeitem ($item)
{
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ )
{
if ($item.id == $arrayCart[i].id)
$arrayCart.splice (i,0);
}
}
But it doesn't work!!

<?php
session_start();
$_SESSION['cart']=array();
$_SESSION['cart']['username'] = 'Admin';
$_SESSION['cart']['Password'] = '123';
.
.
.
?>
For Remove
<?php
session_start();
$_SESSION['cart']=array();
unset ( $_SESSION['cart']['username'] );
.
.
or use Custom Function to Remove...
.
?>
It's Work For Me...
if this code Report Errors Please Comment to Check this...
Please check PHP version

How has no one seen this:
for ($i=0; $i<$arrayCart.length; $++ ){ // <----- lol # $++
Make it $i++
You also need another 2 } to close your if() and for() statements so it's like this:
function removeitem ($item){
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ ){
if ($item.id == $arrayCart[i].id){
$arrayCart.splice (i,0);
}
}
}

Have you tried using this?
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = $item;
You don't need to serialize the item-variable - a Session can store pure Objects, as long as the max. session-size doesn't exceed.
If you want to remove Items from the cart, you should use index-Names - this allows you to find your items faster.
I would probably use something like this:
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
function addItem($itemName){
if(!isset($_SESSION['cart'][$itemName])) {
$_SESSION['cart'][$itemName] = 1;
}else
$_SESSION['cart'][$itemName] ++;
}
}
function removeItem($itemName){
if(isset($_SESSION['cart'][$itemName])) {
if($_SESSION['cart'][$itemName] > 0) {
$_SESSION['cart'][$itemName] --;
}
}
}
function clearCart(){
unset($_SESSION['cart']);
}
In this case, the cart stores each item and its amount. Instead of $itemName, you could also use the item-ID from your database.
To get an item from the cart, you will need this function:
function getItemCount($itemName){
if(isset($_SESSION['cart'][$itemName])) {
return $_SESSION['cart'][$itemName];
}
return 0;
}

Try not pushing to array, because its probably not set yet, but to store to session, create new session var by:
$_SESSION['cart']=serialize($item);
to remove it:
unset($_SESSION['cart']);
EDIT:
Thanks to comments I realized that above code wouldn't store array in session. So, another short solution is to store to session var some JSON. Try this for a short test:
$tmp = array(1,2,3);
$_SESSION['cart']=json_encode($tmp);
print_r(json_decode($_SESSION['cart']));
If that array is associative, you shoud use for decode:
json_decode($_SESSION['cart'], true);

Related

How to convert $_SESSION['myarray'] to regular PHP array

So I have declared a Session array and initialized it with zeroes. It's basically a multidimensional array. However, I'm thinking of converting it to a regular array because everytime I test whether a value exists or not using the in_array() function, it fails. It keeps adding existing values.
<?php
session_start();
$_SESSION['numbers'] = array(
array(0,0,0,0,0), //row1
array(0,0,0,0,0), //row2
array(0,0,0,0,0), //row3
array(0,0,0,0,0), //row4
array(0,0,0,0,0) //row5
);
?>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$userInput = $_POST["num"];
for($r = 0; $r<sizeof($_SESSION['numbers']); $r++){
for($c = 0; $c<sizeof($_SESSION['numbers']); $c++){
$colVal = $_SESSION['numbers'][$r][$c];
insertInputAt($r,$c,$userInput);
}
}
}
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
?>
If I enter lets say 5, it inserts the input 5 to all rows and columns. I get 25 echos of value of 5 even if I put a !in_array() condition
I thought maybe if I parse the $_SESSION['numbers] as a regular array within the insertInputAt() method, the !in_array() condition might work accurately.
Thank you.
Modify your insertInputAt function to this:
function insertInputAt($row,$col,$input){
if(!in_array($input, $_SESSION['numbers'][$row])){ //this fails
echo $input . "<br/>";
$_SESSION['numbers'][$row][$col] = $input;
}
}
First of all, you do not need to initialize $_SESSION['numbers'].
<?php
session_start();
$userInput = $_POST["num"] = 1;
for($r=0;$r<count($_SESSION['numbers']);$r++){
$found = 0;
for($c=0;$c<count($_SESSION['numbers'][$r]);$c++){
if(($_SESSION['numbers'][$r][$c]==0)&&(myfunction($_SESSION['numbers'],$userInput)==0)){
$_SESSION['numbers'][$r][$c] = $userInput;unset($_POST['num']); $found=1;break;
}
}
if($found==1)break;
}
function myfunction($array,$value){
foreach($array as $q){
if(!in_array($value,$q)){
for($i=0;$i<count($q);$i++){
if($q[$i]==0) return false;
}
}
}
}
echo "<pre>";print_r($_SESSION['numbers']);
?>

PHP cookies, add more values to attribute

I'm trying to implement the following feature. When someone reads an article, I want to add a cookie that stores the article id so I can use this in another page. My issue is that if the user sees another article, then the cookie is rewritten so the old id is deleted. I want to keep in the cookie all the ids of the seen articles.
Setting the cookie
<?php
// Check if cookie exists
if( isset($_COOKIE["read"]) ) {
$array = unserialize($_COOKIE['read']);
// Iterate array
found = False;
foreach ($array as $i) {
// Check if doc id already in cookie
if ($array[$i] == $id) {
found = True;
}
}
if (!found) {
array_push($array, $id);
setcookie("read", serialize($array), time()+3600);
}
}
// If cookie does NOT exists
else {
$array = array();
array_push($array, $id);
setcookie("read", serialize($array), time()+3600);
}
?>
Reading the cookie to show that the article is read
<?php
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
if( isset($_COOKIE["read"]) ) {
$array = unserialize($_COOKIE['read']);
// Iterate array
for ($i = 0; $i < count($array); ++$i) {
if ($array[$i] == $id) {
$read = True;
}
else {
$read = False;
}
}
}
else {
$read = False;
}
print "<p>Document ".$row['id']." Title: <b>".$row['title']."</b>";
if ($read == True) {
print("*");
}
print " More Info</p>";
}
?>
This code works but as said overwrites the previous article id. I think I got to use an array. But I don't know how to keep adding values.
UPDATE: I tried to serialize but still no results. I'm trying to see if the id is inside the unserialized array.
Do you want Arrays in cookies PHP
Serialize data:
setcookie('cookie', serialize($idS));
Then unserialize data:
$idS= unserialize($_COOKIE['cookie']);
Try adding a datetime() string to the start of the cookie's name. That way old ones won't get overwritten. Something like:
$date_snippet = date('Y-m-d H:i:s');
setcookie("{$date_snippet}read", serialize($array), time()+3600);

checking if an array is in an array

I am trying to validate whether or not an array is listed in an array.
I am trying to add a product name and url to an session, the session will contain all the products visited by a visitor, but I don't want it to add the same product twice, hence the validation. So if the product is already in the array, I want it to do nothing, but if it doesn't already belong to the array, it needs to be added. This is as far as I got so far. The only issue seems to be the validation.
$viewed_product_url = $viewed_base.$_SERVER['REQUEST_URI'];
if(!isset($_SESSION['products'])) {
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
} else {
$found = false;
foreach($_SESSION['products'] as $each_item) {
while(list($key,$value)=each($each_item)) {
if($key == 'product' && $value == $products_name) {
$found = true;
}
}
}
if($found==false){
echo 'found';
$_SESSION['products'][] = array('product'=>$products_name,'url'=>$viewed_product_url);
}
}
these are the errors I am getting
Warning: Variable passed to each() is not an array or object in C:\xampp\htdocs\customers\msl\product.php on line 10
Warning: Variable passed to each() is not an array or object in C:\xampp\htdocs\customers\msl\product.php on line 10
found
So I just want to know how you can check if an array is already in an multivariate array. Or if there are any other alternatives to achieving what I want here.
Change:
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
to:
$_SESSION['products'] = array(array('product'=>$products_name,'url'=>$viewed_product_url));
so that you get a 2-dimensional array.
However, I think this is a poor data structure. You should make $_SESSION['products'] an associative array, whose key is the product name. So you add elements to it with:
$_SESSION['products'][$products_name] = $viewed_product_url;
and you find products with:
$found = isset($_SESSION['products'][$products_name]);
check with is_array like
if(is_array($_SESSION['products']))
and then you can go with foreach
is_array() function will help you..
http://php.net/manual/en/function.is-array.php
$each_item is not an array. That is the reason for the error.
Try this
$viewed_product_url = $viewed_base.$_SERVER['REQUEST_URI'];
if(!isset($_SESSION['products'])) {
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
} else {
$found = false;
if (in_array($viewed_product_url, $_SESSION['products'])) { {
$found = true;
}
}
}
if($found==false){
echo 'found';
$_SESSION['products'][] = array('product'=>$products_name,'url'=>$viewed_product_url);
}
}

convert array to object in php

In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).

cannot access the array using php

i have created an array using php something like this
$array1=array()
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
it does not print the value.
If nothing else, you should move the inner loop out:
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
for($y=0;$y<5;$y++)
{
print_r($array1[$y]);
}
I just ran this code, the only change i made was putting a semicolon in the first line ;)
<?php
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]="abcd";
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
?>
Output:
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
Based on #Jon's answer:
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
$count = count($array1);
for($y=0;$y<$count;$y++)
{
print_r($array1[$y]);
}
You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
foreach($array1 as $value)
{
print_r($value);
}
Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]='somevalue';
}
print_r($array1);
for($y=0;$y<$i;$y++)
Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i
for($y=0;$y<=$i;$y++)

Categories