473,804 Members | 2,117 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Compare array value with string

16 New Member
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?
Jun 14 '09 #1
17 1892
prabirchoudhury
162 New Member
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
Expand|Select|Wrap|Line Numbers
  1.  
  2. if (in_array($item, $inventory)) {code}
  3.  
:)
Jun 14 '09 #2
toadstool
16 New Member
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
,
Jun 14 '09 #3
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
Expand|Select|Wrap|Line Numbers
  1. $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().
Jun 15 '09 #4
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()
Jun 15 '09 #5
Markus
6,050 Recognized Expert Expert
And you should be using quotes around your array indeces.

Expand|Select|Wrap|Line Numbers
  1. // Good.
  2. $array['index'];
  3.  
  4. // Also good, but will use extra memory.
  5. $array["index"];
  6.  
  7. // Not good. Very bad.
  8. $array[index];
  9.  
Jun 15 '09 #6
toadstool
16 New Member
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?
Jun 15 '09 #7
Markus
6,050 Recognized Expert Expert
You will want array_search() then; it will return the key of the matched item.
Jun 15 '09 #8
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:

Expand|Select|Wrap|Line Numbers
  1. $indexFound = array_search($item,$inventory); 
  2. if($indexFound !== false) {
  3.    $itemLookingFor = $inventory[$indexFound]; 
  4. }
  5.  
=== and !== compare the variable type as well. (bool/string/etc)

Hope that helps,




Dan
Jun 15 '09 #9
toadstool
16 New Member
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.

Expand|Select|Wrap|Line Numbers
  1. function add_to_cart($product_name, $product_qty) 
  2.      { $this->items[$product_name]=$product_qty; }
  3.        //$_COOKIE[product_name]=$_COOKIE[product_name]+$product_qty} 
  4.  
  5.      function update_cart($product_name, $product_qty) 
  6.       { if( array_key_exists($product_name, $this->items) ) 
  7.         { if( $this->items[$product_name]>$product_qty ) 
  8.             { $this->items[$product_name]-=($this->items[$product_name]-$product_qty); 
  9. }
  10.  
  11.           if( $this->items[product_name]<$product_qty ) 
  12.             { $this->items[$product_name]+=abs($this->items[$product_name]-$product_qty); } 
  13.  
  14.           if($qty==0) 
  15.             { unset($this->items[product_name]); } 
  16.         } 
  17.       } 
  18.  
  19.       function remove_from_cart($product_name) 
  20.       { 
  21.        if( array_key_exists($product_name, $this->items) ) 
  22.          { unset($this->items[$product_name]); } 
  23.       } 
  24.  
Jun 15 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2716
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...
8
4497
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)...
19
9531
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!
17
8244
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 ?
3
2301
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
5
37874
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:
12
29482
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
1
1157
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));
3
10559
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
4
4247
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
0
9595
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,...
0
10604
Oralloy
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...
0
10354
jinu1996
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...
1
7643
isladogs
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...
0
6870
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();...
0
5536
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...
1
4314
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
2
3837
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3005
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.