0

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!

3 Answers 3

1

Use basename() and in_array():

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

Demo.

Sign up to request clarification or add additional context in comments.

1 Comment

@Benn: Glad to have been of help!
1

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]);
      }
}

2 Comments

Yes, I was almost there with this , thnx much!
I personally think using basename() is cleaner (as shown in my answer) Also, I'd use !== FALSE instead of == true.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.