PHP splitting array into two arrays based on value

前端 未结 5 1078
小蘑菇
小蘑菇 2021-02-19 06:43

I have a PHP array that I am trying to split into 2 different arrays. I am trying to pull out any values that contain the word \"hidden\". So one array would contain all the v

相关标签:
5条回答
  • 2021-02-19 07:21

    Maybe it's just me, but I would go for the clarity of regular expressions...

    foreach($myArray as $item) {
        if (preg_match("/hidden$/i", $item)) {
            array_push($arr2, $item);
        } else {
            array_push($arr1, $item);
        }
    }
    
    0 讨论(0)
  • 2021-02-19 07:22

    This should do the trick:

    $myArray = array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
    $secondaryArray = array();
    
    foreach ($myArray as $key => $value) {
        if (strpos($value, "hidden") !== false) {
            $secondaryArray[] = $value;
            unset($myArray[$key]);
        }
    }
    

    It moves all the entries that contain "hidden" from the $myArray to $secondaryArray.

    Note: It's case sensitive

    0 讨论(0)
  • 2021-02-19 07:31

    You can use array_filter:

    function filtreHiddens($e) {
        if (isset($e['hidden']) && $e['hidden']) return true;
        else return false;
    }
    
    function filtreNotHiddens($e) {
        if (isset($e['hidden']) && !$e['hidden']) return true;
        else return false;
    }
    
    $arrayToFiltre = array(
        array('hidden' => true, 'someKey' => 'someVal'),
        array('hidden' => false, 'someKey1' => 'someVal1'),
        array('hidden' => true, 'someKey2' => 'someVal3'),
    );
    
    $hidden = array_filter($arrayToFiltre, 'filtreHiddens');
    $notHidden = array_filter($arrayToFiltre, 'filtreNotHiddens');
    
    print_r($hidden);
    print_r($notHidden);
    
    0 讨论(0)
  • 2021-02-19 07:42

    You can use array_filter() function:

    $myArray = array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
    
    $arr1 = array_filter($myArray, function($v) { return strpos($v, 'hidden') === false; });
    $arr2 = array_diff($myArray, $arr1);
    

    Demo

    0 讨论(0)
  • 2021-02-19 07:42
    $myArray = Array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
    $arr1 = array();
    $arr2 = array();    
    foreach ($myArray as $item) {
        if (strpos($item, "hidden") !== false) {
            $arr1[] = $item;
        } else {
            $arr2[] = $item;
        }
    }
    

    This solution checks if 'hidden' present at current item, if no, move to $arr1 else to $arr2

    0 讨论(0)
提交回复
热议问题