How can i chec开发者_如何学Pythonk if a string is already present withing an array before adding to it in php?
say if array is $value
$value[0]="hi";
$value[1]="hello";
$value[2]="wat";
I want to check if value exists in it before adding it to it.
$s='hi';
if (!in_array($s, $value)) {
$value[]=$s;
}
in_array()
checks if that value (1st parameter) is in the array (2nd parameter), returns boolean (!
negates it)$value[]=$s
will add the value to the array with the next index
There is another tricky way if you want to add a bunch of values into an array, but only if they are not there yet. You just have to organize these new values into another array and use a combination of array_merge()
and array_diff()
:
//your original array:
$values=array('hello', 'xy', 'fos', 'hi');
//the values you want to add if they are not in the array yet:
$values_to_add=array('hi', 'hello', 'retek');
$values=array_merge($values, array_diff($values_to_add, $values));
//$values becomes: hello, xy, fos, hi, retek
You can use in_array($searchstring, $array)
in_array("hello", $value)
returns true
in_array("hllo", $value)
returns false
http://php.net/manual/en/function.in-array.php
http://php.net/manual/en/function.in-array.php
if(in_array("hello", $value)) { // needle in haystack
return TRUE;
}
in_array - Checks if a value exists in an array.
In case of in_array($searchstring, $array)
, remember, the comparison is done in a case-sensitive manner, if the $searchstring
is a "String"
Example :
- in_array("wat", $value) returns true
- in_array("what", $value) returns false.
// Observe carefully
- in_array("WAT", $value) returns false.
if you're going to create a Set, it's much better to use array keys instead of values. Simply use
$values["whatever"] = 1;
to add a value, no need to check anything.
精彩评论