I have an array containing the various products
$inventory = array();
$inventory[0] = "whatever1" ;
etc
I have an array containing various values
$quantity = array(100,200,3 00);
I call in a value from a form $_POST[itemname]; say
I assign a variable
$var1="$_POST[itemname]";
I want to compare the input value with the array value e.g.
for($i = 0;$i<$inventory _total;$i++) {
if($inventory[$i] == $item) { code }
}
However, this is always negative as I believe I cannot compare an array item with a string.
The only thing I've found so far is the "mplode" statement
But I want to compare individual array items not a string composed of all of them.
Can anyone suggest a simple conversion so that I can compare values?
17 1892
hey
I want to compare the input value with the array value e.g.
for($i = 0;$i<$inventory _total;$i++) {
if($inventory[$i] == $item) { code }
}
1. if you are checking $item value existing in $inventory array (if i am right) then you would use -
-
if (in_array($item, $inventory)) {code}
-
:)
I'm comparing the value in a form with the contents of an array of text items
If (the array item $inventory) equals the form item ($item1))
then {change/update the value in the $quantity array}
e.g.
for($i = 0;$i<$inventory _total;$i++) {
if($inventory[i] == $item) {
$quantity[$i]=($quantity[$i] + $value); }
}
when I put if($inventory[$i] ==$item) then the answer is false;
when I put if($inventory[$i] = $item) then all values in the array $quantity are updated
,
code green 1,726
Recognized Expert Top Contributor
prabirchoudhury is correct.
There is no need to loop through the array 'by hand'. in_array() does that for you.
There is also no need for the quotes - $var1="$_POST[itemname]";
And there should be no problem comparing strings with array elements.
I would qualify your $_POST variables before using them.
By that I mean use trim() and strip_tags() and empty() and isset() and possibly is_string() and is_numeric().
code green 1,726
Recognized Expert Top Contributor
Oh yes.If using in_array you will also need to ensure the 'case' matches.
Do this using strtolower() or strtoupper()
Markus 6,050
Recognized Expert Expert
And you should be using quotes around your array indeces. -
// Good.
-
$array['index'];
-
-
// Also good, but will use extra memory.
-
$array["index"];
-
-
// Not good. Very bad.
-
$array[index];
-
Thank you everyone for your input. You have given me a lot to think about.
I apologize for not indicating this was php.
I have considered the if (in_array($item , $inventory)) {code} suggested by many of you, but I am not sure how I would then update the related $quantity[i] for the item thus found.
If $inventory[i] = $item[i] then I want to update (add to) $quantity[i]
If I use in_array, I can determine that it is in the array, but how do I identify the specific item?
Markus 6,050
Recognized Expert Expert
You will want array_search() then; it will return the key of the matched item.
dlite922 1,584
Recognized Expert Top Contributor
a common mistake when using array_search(). If your item is the first element, index 0, then the if statement will treat it as false. You need a strict (type) comparison: -
$indexFound = array_search($item,$inventory);
-
if($indexFound !== false) {
-
$itemLookingFor = $inventory[$indexFound];
-
}
-
=== and !== compare the variable type as well. (bool/string/etc)
Hope that helps,
Dan
Looks good, I'll try it out, I am trying an alternative approach using a class to update the value, but haven't yet managed to increment the value e.g. if further entries are made. -
function add_to_cart($product_name, $product_qty)
-
{ $this->items[$product_name]=$product_qty; }
-
//$_COOKIE[product_name]=$_COOKIE[product_name]+$product_qty}
-
-
function update_cart($product_name, $product_qty)
-
{ if( array_key_exists($product_name, $this->items) )
-
{ if( $this->items[$product_name]>$product_qty )
-
{ $this->items[$product_name]-=($this->items[$product_name]-$product_qty);
-
}
-
-
if( $this->items[product_name]<$product_qty )
-
{ $this->items[$product_name]+=abs($this->items[$product_name]-$product_qty); }
-
-
if($qty==0)
-
{ unset($this->items[product_name]); }
-
}
-
}
-
-
function remove_from_cart($product_name)
-
{
-
if( array_key_exists($product_name, $this->items) )
-
{ unset($this->items[$product_name]); }
-
}
-
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Phil Powell |
last post by:
/*--------------------------------------------------------------------------------------------------------------------------------
Parameters:
$formField1: The name of the first array
$formField2: The name of the second array
$formField1CompareWith: String to use as my comparison basis for first
array. Defaults to using $val unless it's 'key'
$formField2CompareWith: String to use as my comparison basis for
second array. Same default as...
|
by: Kenneth Baltrinic |
last post by:
I am trying to compare values coming out of a database record with known
default values. The defaults are in an array of type object (because they
can be of any basic data type, I am not working with weird stuff, just
strings, int, bools and DataTime values) My fields values for this record,
for convenience are also in an array of objects. Now I am trying to write
code like the following.
private void processData (object d, object a)...
|
by: David zhu |
last post by:
I've got different result when comparing two strings
using "==" and string.Compare().
The two strings seems to have same value "1202002" in
the quick watch, and both have the same length 7 which I
have tried to print out by debug.writeline().
But the "==" operator results false, and string.Compare()
results true.
Somebody helps me!
|
by: bengamin |
last post by:
Hi,
I have a C# class and two instance of the class;
the class have some property.
I want to compare the property value of the two instance
How should i do? override == ? use delegate ?
|
by: Sam |
last post by:
Hi Everyone,
I have a stucture below stored in an arraylist and I want to check user's
input (point x,y) to make sure there is no duplicate point x,y entered
(string label can be duplicated). Is there a way to compare the new input
point x,y without having to a loop and compare the whole object in the array
list. I can't use the indexof method because it would compare the whole
object.
Public Structure
| |
by: Jason |
last post by:
Is there a mechanism in VB.NET that allows something like:
If myVar In ("A","B","C") Then...
The way I'm doing it now is:
Select Case myVar
Case "A","B","C"
Or like this:
|
by: Assimalyst |
last post by:
Hi,
I have a working script that converts a dd/mm/yyyy text box date entry
to yyyy/mm/dd and compares it to the current date, giving an error
through an asp.net custom validator, it is as follows:
function doDateCheckNow(source, args)
{
var oDate = document.getElementById(source.controltovalidate); //
dd/mm/yyyy
|
by: Jeff Williams |
last post by:
How do I compare a array string value with an string
private bool CheckRole( string sRoleName )
{
bool lIsInRole;
lIsInRole = false;
AppDomain myDomain = Thread.GetDomain();
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
Array wbirFields = Enum.GetValues(typeof(WindowsBuiltInRole));
|
by: raylopez99 |
last post by:
This is an example of using multiple comparison criteria for IComparer/
Compare/CompareTo for List<and Array.
Adapted from David Hayden's tutorial found on the net, but he used
ArrayList so the format was different.
Basically you can sort a class having members LastName (string),
FirstName (string) and Age (int) according to whether you want to sort
by Last Name, First Name or Age, using the .Sort function
|
by: toadstool |
last post by:
I have an array containing the various products
$inventory = array();
$inventory = "whatever1";
etc
I have an array containing various values
$quantity = array(100,200,300);
I call in a value from a form $_POST; say
I assign a variable
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |