-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);
3
  • What have you come up with so far? Commented Dec 20, 2020 at 9:04
  • 1
    $i = array_search($check, $sample); $r = array_slice($sample, 0, $i); $n = array_slice($sample, $i); Commented Dec 20, 2020 at 10:04
  • implemented by for loop, need solution using array function- @Ro Achterberg Commented Dec 20, 2020 at 10:57

1 Answer 1

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.

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

3 Comments

You tagged in PHP 7.4 but you didn't even use the arrow function
Sorry about that, not aware of arrow function. Can you please update the answer.:-@Dharman
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.