Issue with in_array() not stopping multiple entries of the same value
5 replies, posted
I'm currently making a small webapp for myself to make my job at work easier by automatically sorting / altering data. Right now I'm simply just trying to use the built in PHP function of in_array to check if a value already exists within a array. Right now it just keeps adding the same value in. The data is loaded from a CSV file the user chooses and parses the data. One the the variables is vendors we get product from so I want to pull each vendor name into a select option to be able to sort vendor name or block them from loading into my list.
if(in_array($vendor,$brand) == FALSE){ array_push($brand, $vendor); echo "<p>Adding: " . $vendor . "</p>";}
The above code is what I've got to check if the value is already in the array. $brand is set with $brand = Array(); and $vendor is loaded in from the CSV.
Results Now: Brand1, Brand1, Brand1, Brand1, Brand1, Brand1, Brand2, Brand2, Brand2, Brand2, Brand2, etc.
What i'd like: Brand1, Brand2, Brand3, Brand4, Brand5, etc.
I'm not super familiar with PHP just learning a bit to make this app so I can use it anywhere from a browser so I might be making a stupid mistake
That part of code seems fine, so it must be $vendor not getting properly set. Can you post the surrounding code that handles the data from the moment it's read from the file?
Just overlooked the code again this morning... It was a stupid stupid error haha I was setting the $brand = Array(); inside of my while loop that reads the CSV file so I kept getting an empty array and what appeared to be multiple entries..
Is there a reason your code is all on one line, or did you just do that when pasting it here? Also I'm not sure if you know, but since in_array only returns a boolean value, you can just do:
if(!in_array($vendor,$brand))
It's a dumb habit of mine to where if I have a small if statement that just checks something small I'll write it on one line. Everything else I do format properly.
PHP is more loose than strict, your "== false" would be true for "0 == false" and "array() == false", which is why PHP also has a triple equals comparison, which you need for functions like strpos
Sorry, you need to Log In to post a reply to this thread.