简体   繁体   中英

How to unset array key if it contains certain string from search array?

My array print looks like this print_r($myArray);

Array
(
     [http://link_to_the_file/stylename2.css] => Array
        (
            [mime] => text/css
            [media] => 
            [attribs] => Array
                (
                )

        )

    [http://link_to_the_file/stylename1.css] => Array
        (
            [mime] => text/css
            [media] => 
            [attribs] => Array
                (
                )

        )

    [http://link_to_the_file/stylename5.css] => Array
        (
            [mime] => text/css
            [media] => 
            [attribs] => Array
                (
                )

        )
)

I need to find stylename 2 and 5 and unset them but I would like to find them only by their names and not the full array key. So I placed my search terms in array.

$findInArray = array('stylename2.css','stylename5.css');


foreach($myArray as $path => $file ){


    //  if $path contains a string from $findInArray 
       unset $myArray [$path];

}

What would be the best approach to this ? I tried array_key_exists but it matches only exact key value. Thank you!

try this:

$findInArray = array('stylename2.css','stylename5.css');
foreach($myArray as $path => $file ){
      foreach($findInArray as $find){
           if(strpos($path, $find) !== false)
              unset($myArray[$path]);
      }
}

you could use the PHP in_array() function for this.

foreach($myArray as $path => $file) {
    if(in_array(basename($path), $findInArray)) {
        unset($myArray[$path]);
    }
}

Use basename() and in_array() :

foreach($myArray as $path => $file ){
    $filename = basename($path);
    if (in_array($filename, $findInArray)) {
        unset($myArray[$path]);
    }
}

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM