Jump to content

Removing Angry Animal Variables from Array


soma56

Recommended Posts

I can see how we can remove specific variables within an array:

 

<?php

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
?>

 

What if we wanted to completely remove variables based on only a partial variable name?

 

<?PHP
$animals_of_php = array("Angry Dog", "Smiley Cat", "Mad Moose", "Nice Dog", "Nice Cat", "Ticked Off Flea", "Psycho Mouse", "Happy Skunk", "Laughing Ants", "Snappy Snake");
$only_nice_animals = ??
?>

 

Would it be smarter to filter out what you want before the array is created or simply filter the array after it's been created?

 

What I'm trying to figure out, in a hopefully entertaining way, is what type of function is needed in providing only partial variables: "Angry", "Mad", "Ticked", "Psycho" and "Snappy" - resulting in removing the entire variable: "Angry Dog", "Ticked Off Flea", "Psycho Mouse",  "Snappy Snake"

 

 

Link to comment
Share on other sites

I'll try and be more specific if it helps. Let's say I knew in advanced what the a partial name of the variable within the array that I don't want. Is that enough information to unset the variable?

 

I don't have a use for the word "Bad"

If my array comes in with "Bad Dog", "Bad Cat", "Bad Bear" - what's the best way to, not only the word "Bad", but whatever else follows within a list?

Link to comment
Share on other sites

You mean something like this?:

 

$arr = array("Bad Dog", "Bad Cat", "Bad Bear", "Nice Bear", "Nice Dog");
foreach($arr as $key => $val){
    if(strpos(strtolower($val), 'bad') !== false){
        unset($arr[$key]);
    }
}

print_r($arr);

 

Link to comment
Share on other sites

Nice, I've found a way to make it work, but what about adding more conditions?

 

<?PHP
    if(strpos(strtolower($val), 'bad') !== false){
?>

 

Perhaps an array in that spot?

 

<?PHP
$angry_animals = array('bad', 'ugly','mad');
    if(strpos(strtolower($val), '$angry_animals') !== false){
?>

 

i haven't tried it yet but am I on the right track?

Link to comment
Share on other sites

Make a function like this:

 

function strpos_array($haystack, $search){
    foreach($search as $term){
        if(strpos($haystack, $term) !== false){
            return true;
        }
    }
    return false;
}

 

Then use it like this:

 

$arr = array("Bad Dog", "Bad Cat", "Bad Bear", "Nice Bear", "Nice Dog");
$angry_animals = array('bad', 'ugly', 'mad');

foreach($arr as $key => $val){
    if(strpos_array($val, $angry_animals)){
        unset($arr[$key]);
    }
}

print_r($arr);

Link to comment
Share on other sites

  • 4 weeks later...

For anyone that needs to have this done as far as case insensitive goes I figured it out:

 

function strpos_array($haystack, $search){
    foreach($search as $term){
        if(stristr($haystack, $term) !== false){
            return true;
        }
    }
    return false;
}

$arr = array("Bad Dog", "Bad Cat", "Bad Bear", "Nice Bear", "Nice Dog");
$angry_animals = array('bad', 'ugly', 'mad');

foreach($arr as $key => $val){
    if (strpos_array($val, $angry_animals)){
        echo $val;
    }
}

 

I simply replaced 'strpos' with 'stristr'. The code above echoes out the 'angry_animals'.

 

Thanks again for everyone's help on this one.

Link to comment
Share on other sites

strpos() (and its alternatives such as stristr()) may not be appropriate for this usage since they do not know when "bad" is a whole word in the string ("bad dog") vs. part of another word, ("good badger"). That function would incorrectly filter out "good badger" because of the "bad" in the word "badger". In this case you will want to use a regular expression.

 

This is a little more flexible. The function takes the input array, an array of words to use for filtering, and an optional third parameter to determine whether you want the return value to be the array of values that are not filtered(default) or the array fo the filtered values.

function filterArrayByWords($inputAry, $excludeWordsAry, $returnInclude=true)
{
    $excludeAry = array();
    $includeAry = $inputAry;
    foreach($includeAry as $keyInt => $valueStr)
    {
        foreach($excludeWordsAry as $excludeWordStr)
        {
            //Check for exclude word using word boundrys
            if(preg_match("/\b{$excludeWordStr}\b/i", $valueStr)!=0)
            {
                $excludeAry[$keyInt] = $valueStr;
                unset($includeAry[$keyInt]);
                break;
            }
        }
    }
    return ($returnInclude) ? $includeAry : $excludeAry;
}
  
$animals = array("Bad Dog", "Bad Cat", "Bad Bear", "Nice Bear", "Nice Dog", "Good Badger");
$angry_animals = array('bad', 'ugly', 'mad');

print_r(filterArrayByWords($animals, $angry_animals));
//Output: Array ( [3] => Nice Bear [4] => Nice Dog [5] => Good Badger )

print_r(filterArrayByWords($animals, $angry_animals, false));
//Output: Array ( [0] => Bad Dog [1] => Bad Cat [2] => Bad Bear )

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.