473,387 Members | 1,553 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Compare array value with string

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,300);

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 1862
prabirchoudhury
162 100+
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
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 Expert 1GB
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 Expert 1GB
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 Expert 4TB
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
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 Expert 4TB
You will want array_search() then; it will return the key of the matched item.
Jun 15 '09 #8
dlite922
1,584 Expert 1GB
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
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
I can get a value here, but I want to increment the value if further entries are made, which would require storing the value. I initially approached it from the idea of updating an array of values.
Still learning how to manage these functions.
Jun 15 '09 #11
Hi there,
I tried this

Expand|Select|Wrap|Line Numbers
  1. $indexFound = array_search($item,$inventory);  
  2.   if($indexFound !== false) { 
  3.   $itemLookingFor = $inventory[$indexFound]; 
  4.   echo "<p> $itemLookingFor= ".$itemLookingFor."</p>";  
  5.   echo "<p> $inventory[$indexFound]= ".$inventory[$indexFound]."</p>";
  6.   }
  7.   else
  8.   { echo "<p> THIS DOESN'T WORK </p>";
  9.   }
  10.  
  11. should I say what message came up?
  12. Too bad, I do appreciate all the comments.  I'm learning a lot here
  13.  
Jun 15 '09 #12
When one considers the problem
I have a value and some input from a form
I want to add that input to the original value and store it so that I can add further values.
One wouldn't think that would be difficult.
Jun 15 '09 #13
dlite922
1,584 Expert 1GB
which message came up? It depends. was your string in the array? if so, you'll see the value twice, if not it will yell at you for not working.

:)

Your welcome anytime,

Dan


EDIT: make that three times because your first echo uses double quotes, which parses that $itemLookingFor variable before the equal sign :P
Jun 15 '09 #14
In answer to your questions. The item was in the array.
I just rechecked.
And the value didn't come up at all the other one did.
Which is a shame, because everyone seems to be trying to help.
Jun 15 '09 #15
Well
Anyone that resolves the problem of adding and updating these values ought to get bonus points because despite seeming a relatively simple problem, seems to be just out of reach.
Thanks everyone for your input, it has been interesting so far.
Jun 16 '09 #16
The first statement (I believe) cannot work:
Expand|Select|Wrap|Line Numbers
  1. $var1="$_POST[itemname]";
... just remove the quotes and add a $ before the itemname
Jun 16 '09 #17
Actually, I had no problem bringing in the form value.
But getting the $value to work, was more difficult. Sometimes it failed even though the code was unchanged.
Adding to previous totals and retaining the new value evaded me,even with cookies the result was unstable.
Jun 16 '09 #18

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

Similar topics

0
by: Phil Powell | last post by:
/*-------------------------------------------------------------------------------------------------------------------------------- Parameters: $formField1: The name of the first array $formField2:...
8
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...
19
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...
17
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
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...
5
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
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...
1
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();...
3
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...
4
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...

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.