-2

There is an array in php

$sampleArray = array('first' => 'first', 'second' => 'second', 'third' => 'third');

I need to splitting the array based on value $check, if the $check is 'second', then the array need to be split like this

$requiredArray = array('third'=>'third')
$nonReqArray = array('first'=>'first','second'=>'second')

if the $check is 'third' then the $requiredArray will be empty. Please suggest the solution to this? Tried with this

$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check) { 
     
        if($key > $check){
            $requiredArray[$key] = $key;
        }else{

            $nonReqArray[$key] = $key;

        }
        return true;
    }, 
    ARRAY_FILTER_USE_KEY);
ubm
  • 636
  • 11
  • 21

1 Answers1

0

Usually solved with for loops. But we can solve by array_filter array function. The main issue is indexing is not numerical, so comparing is not easy.

    $cmp = false;
    $afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check, &$cmp) { 
             
                if($cmp){
                    $requiredArray[$key] = $key;
                }else{

                    $nonReqArray[$key] = $key;

                }
               if($key == $check){
                  $cmp =true;
                }
                return true;
            }, 
            ARRAY_FILTER_USE_KEY);

This worked for me.

ubm
  • 636
  • 11
  • 21
  • You tagged in PHP 7.4 but you didn't even use the arrow function – Dharman Dec 20 '20 at 14:18
  • Sorry about that, not aware of arrow function. Can you please update the answer.:-@Dharman – ubm Dec 20 '20 at 14:30
  • No, I don't find your answer that useful, but I also do not think it's not useful. I neither downvote, nor upvote, but I also see no point in trying to change it. We already have such answers and they have been linked as a duplicate. If you want to learn about arrow functions you can check out the PHP manual. – Dharman Dec 20 '20 at 14:31