Search code examples
phparraysarray-map

How to find value in PHP array


I have a few attributes in array. For example size for clothes. I want to check if I have attributes or not. If not I want to display error in file. And the problem is. Why I have error even I compare the same string?

Please, check my code below.

foreach ($attributeToCheck as $singleAttributeToCheck) 
            {
                if(!array_search(strtolower($singleAttributeToCheck), array_map('strtolower', array_column($attributes, 'name')))){            
                    $this->errorLog('*  ERROR   *   There is no:' . $singleAttributeToCheck);
                    return FALSE;
                }                
            }

In $attributeToCheck I have those value:
0: "Black"
1: "S"

In strtolower($singleAttributeToCheck) I have value:
"s"

array_map('strtolower', array_column($attributes, 'name')) looks like this:
0: "s"
1: "m"
2: "l"

Why I go to errorlog? I have string "s" in my array. Thanks for help.

Kind regards


Solution

  • array_search() function finds the value and return its key and that is not what is needed here, instead you must use in_array() function which will return the value to the function

    <?php
    function a($v){
        return(strtolower($v));
    }
    $attributeToCheck  = array("Black","S");
    $attributes =   array('s','m','l');
    $array = array_map('a',$attributeToCheck);
    foreach ($array as $value) {
        if(!in_array($value,$attributes)){
            echo "Not Found<br>";
        }
        else{
            echo "Success";
        }
    }
    ?>
    

    enter image description here

    In the mentioned above output the Not Found is the result of checking Black in the array and Success is for checking S.