php in array question
I have this code here:
if (in_array('mystring', $entry->getCategories()->getValues()))
{
... //do somethingA
This works.
However, I want to allow somethingA to run, if "mystring" OR "mYstring" or "MYSTRING" is the case.
So I've tried like so:
if (开发者_如何学Cin_array(array('OCC', 'OCc','Occ', 'occ', 'ocC','oCC', 'oCc', 'OcC'), $entry->getCategories()->getValues()))
{
But I get nothing returned. What am I missing here?
Thanks a lot, MEM
in_array()
cannot compare the values of two arrays, nor can it compare strings case-insensitively. From the manual:
If
needle
is a string, the comparison is done in a case-sensitive manner.
You can try this trick instead. Map strtolower()
to the categories array so everything is in lowercase, then search the array for the lowercase string:
$cats_lower = array_map('strtolower', $entry->getCategories()->getValues());
if (in_array('mystring', $cats_lower))
{
// Do something
}
Something which is more future proof (try including all possible combinations of long strings), try:
if (in_array(strtolower('myStrIng'), array_map(strtolower, $entry->getCategories()->getValues()))) {
// do something
}
foreach($entry->getCategories()->getValues() as $val) {
if(preg_match("/$val/i", "occ") {
somethingA();
}
}
精彩评论