Checking session array for value (PHP in_array) - php

My simple shopping cart stores products id's in a session array.
I'm trying to set up an if/else statement to enable/disable my "Add to cart" button based on the product ID being in array or not.
<?php
session_start();
//Show cart array
print_r($_SESSION['cart']);
echo '<br><br>';
//Return "yes" or "no"
$panier = $_SESSION['cart'];
$produit = "5";
if (in_array($produit, $panier)) {
print "yes man!";
}
else {
print "no man!";
}
?>
I'm making sure 5 is part of the array values by displaying them of this test page, but the second part always returns "no man!"
looks simple enough to me. What am i doing wrong ?
print_r command output is
5,5
no man!
that is because i've added 2 of the "5" product id to my cart
If I change this line
print_r($_SESSION['cart']);
for
print_r($_SESSION);
I get
Array ( [cart] => 5,3,3,3,3,3,3,3,2 )
no man!

So, according to you, $_SESSION['cart'] = "5,5"; and it means it is a string. So the right code to look up your value is strpos():
$pos = strpos($produit, $_SESSION['cart']);
if($pos !== false) {
echo "YES";
}
else {
echo "NO";
}
BUT there's a huge risk to get the wrong answer for this. Imagine, you have two products in your cart - first with id 15 and the other with id 7. You'll be looking for id 5. What would the above code output? It will output "YES".
So, instead of using a string, I suggest you use multidimensional array (if you want to stick with sessions). In this particular case then, the variable $_SESSION["cart"] would be an array and with adding new products it would look like this:
$_SESSION["cart"] = array(); // initial value, don't call it every time or it'll flush your array
$_SESSION["cart"][] = $product_ID;
Or similar to it.
print_r will give you a similarly-looking output:
Array(
cart => array(
[0] => 5
[1] => 17
[2] => 5
)
)
Then, in_array should work. But, plan your storing wisely ;)

As jon asked it is better put always the output of your program But for now I am suspecting your problem is in the in_array check this link A problem about in_array it might help

Related

Can't call array record in second page PHP

I've two page , first page there's an array data and second page I want call array data
Like this
First page index.php
$array_data[]=$array_tmp;
print_r($array_data); // array can display in this page
$_SESSION['one'] = $array_data;
Second page next.php
I want to call array from first page
session_start();
$array = $_SESSION['one'];
foreach( $array as $key => $value ) {
echo $value;
}
print_r($_SESSION['one'])
May I know what's wrong? As array can't display in second page.
I think you should change this code $array = $_SESSION['one']; to $array[] = $_SESSION['one'];. I`m not sure & not tested as well but I think so. Hope this will help.
You need to start the session if you already have not. Without starting the session, you can't assign value to the session variable. So the first code snippet would be like this:
session_start();
$array_data[]=$array_tmp;
print_r($array_data); // array can display in this page
$_SESSION['one'] = $array_data;
Second snippet looks fine but the last line is missing a semicolon. It might sound silly, but that can prevent the whole script from running. Here's the code fixed.
session_start();
$array = $_SESSION['one'];
foreach( $array as $key => $value ) {
echo $value;
}
print_r($_SESSION['one']);
Post more code if this does not work.

Behavior of array_search()

I am using function array_search to unset elements from a session array. Problems: if the key found is 0, returns false; if is selected the last element from the "list", it doesn't take it off from the browser's page but it is deleted from the array (works fine with the other elements); if i print out the $key it doesn't show the right key, but a value that keeps growing every time the result is a key that has been already "used".
The first and second problems are of most interest to me. The code that unsets elements from array seem correct and logic to me so i need help again...
So I've set up a pagination that retrieves data from a DB table. Everything prints fine.
while($row=mysqli_fetch_assoc($query))
{
echo "<tr><td>".$row['ID']."</td><td>".$row['name']."</td><td>";
if($row['stoc']==0) echo "Stoc 0</td></tr>";
else echo "Add this</td></tr>";
}
Then if isset(GET['item']) ("Add this" button), build a session array and add to it the items selected one by one:
if(isset($_GET['item']))
{
$cod=$_GET['item'];
$item_q=mysqli_query($conn, "SELECT name FROM mousi WHERE cod='$cod'");
$item_f=mysqli_fetch_assoc($item_q);
if(!in_array($item_f['name'],$_SESSION['prod'])) $_SESSION['prod'][]=$item_f['name'];
foreach($_SESSION['produse'] as $elm)
echo $elm."<a href='mousi.php?item=$cod&del=$elm'>Delete</a><br />";
}
And finally there is an if isset(GET['del']) condition writen before if isset(GET[item]) and this GET[del] unsets an element from the array $_SESSION['prod']:
if(isset($_GET['del']))
{
$key=array_search($_GET['del'], $_SESSION['prod']);
if($key!==false)
{
unset($_SESSION['prod'][$key]);
echo $key." 'selected' key<br />"; //why would this grow like the last result is stored?
print_r(array_values($_SESSION['prod'])); //just to see if the elements are actually deleted and they are, except the first one (key=0)
}
else echo "Key not found";
}
Thank you in advance!

iterating through a changeable JSON array

I'm working on a web application that takes its data from a web page using the Yahoo Query Language API to return a JSON array. I've hit a block in that sometimes, when there is only one "race" on the page, the array is setup differently and I can't iterate through it in some circumstances. Let me explain in an example.
Array layout for a page with mutiple races
Array (
[div] => array (
[0] => array (
['venue_id'] = 02222
['venue_name'] = 'Hove'
['race_id'] = 9222
)
[1] => array (
['venue_id'] = 03333
['venue_name'] = 'Romford'
['race_id'] = 2442
)
//...and so on
)
)
Array layout for a page with just one race
Array (
[div] => array (
['venue_id'] = 02222
['venue_name'] = 'Hove'
['race_id'] = 9222
)
)
In the application, I'm currently using a simple foreach statement to iterate through the array. However, this obviously wont work with the second example and I need a workaround.
Example of foreach statement
foreach($result['div'] as $race) {
echo 'Venue ID: '.$race['venue_id'];
echo 'Venue Name: '.$race['venue_name'];
echo 'Race ID: '.$race['race_id'];
}
Any help would be massively appreciated!
Dan
I'd do this..
if(!isset($array['div'][0]))
$array['div'] = array($array['div']);
This way I do not have to have two iteration methods.
Take a look at the count value which is returned with all YQL result sets. If there is only one result, then force it to be an array (with one item) just like when there are multiple results.
So, something likeā€¦
if ($yql['query']['count'] == 1) {
$yql['results']['data'] = array($yql['results']['data']);
}
This way, the rest of your script doesn't need to care about the structure of the results.
What about:
if ( isset($result['div'][0])){
//first iteration method
} else{
//second iteration method
}
As simple as:
function format_race($race) {
echo 'Venue ID: '.$race['venue_id'];
echo 'Venue Name: '.$race['venue_name'];
echo 'Race ID: '.$race['race_id']
}
if (isset($result['div']['venue_id'])) {
format_race($result);
} else {
array_map('format_race', $result);
}
This also has the advantage of abstracting the data manipulation in an external function, which can come handy in many situations.
Please note that here I'm abusing a little of array_map, probably using foreach($result as $race) would make your program more readable for other php programmers if all you have to do is just printing.

Removing items from a session

I'm having trouble removing items in a session array in a shopping cart project. The following code should take the selected item and remove it from the session. However the end result is just the same session as before with nothing removed. I've seen similar problems by googling, but haven't found a working solution yet. Here is the stripped down code:
<?php
session_start();
$removeditem = $_GET['item']; // this identifies the item to be removed
unset($_SESSION['stuff'][$removeditem]); // "stuff" is the existing array in the session
?>
Here are what print_r gives for the following (using "7" as the example of the removed item):
$removeditem:
7
$_SESSION['stuff'] (before and after removal)
Array
(
[0] => 7
[1] => 24
[2] => 36
)
Am I missing something obvious?
You are deleting the item with the KEY being equal to $removedItem. It seems to me from your example that you are trying to delete the element that has the VALUE equal to removedItem. In this case, you need to do a foreach loop to identify the key and then delete it.
foreach($_SESSION['stuff'] as $k => $v) {
if($v == $removeditem)
unset($_SESSION['stuff'][$k]);
}
You need to first get the key of the element and then unset it. Here's the code you should use:
if(($key = array_search($removeditem, $_SESSION['stuff'])) !== FALSE)
unset($_SESSION['stuff'][$key]);
The most simple way is:
<?php
session_start();
$removeditem = $_GET['item'];
$temp = array_flip($_SESSION['stuff']);
unset($_SESSION['stuff'][$temp[removeditem]]);
?>
P.S. Not tested... just a concept.
7 is value in the array not a key, so unsetting something with key 7 will not do a job.
What you have to do is compare each item in the array with one you want to delete ($_GET['item']) , retrive its key and unset it.

How to search array for duplicates using a single array?

I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )
There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.

Categories