2

How can I get all previous element before a specific array key.

Here is my array:

$key = 256;

$array = (
125 => array(571, 570), 
284 => array(567, 566),
256 => array(562, 560),
110 => array(565, 563),
);

Now I want result like this:

$array = (
125 => array(571, 570), 
284 => array(567, 566)
);
8
  • possible duplicate here stackoverflow.com/questions/41713639/… Commented Nov 27, 2017 at 2:05
  • Please read again. It doesn't solve my problem.. Commented Nov 27, 2017 at 2:09
  • 1
    @MDAbubakar Please rephrase your question, do you mean the elements before a given key? Because that's the results you are wanting. Commented Nov 27, 2017 at 2:12
  • Yes... I want to get elements before given key Commented Nov 27, 2017 at 2:15
  • This is sure to be a duplicate. I'll have a quick look. Commented Nov 27, 2017 at 5:34

4 Answers 4

3

You can iterate through and push values to a newArray until you hit the key you are searching for:

$Key = 256;

$array = array(
"125" => array(571, 570), 
"284" => array(567, 566),
"256" => array(562, 560),
"110" => array(565, 563),
);

$newArray = [];

foreach($array as $key => $value) 
{   
  if($key == $Key) break;
  $newArray[$key] = $value;
}

print_r ($newArray); 
/*
=> Array ( 
    [125] => Array ( [0] => 571 [1] => 570 ) 
    [284] => Array ( [0] => 567 [1] => 566 ) 
   )
*/
Sign up to request clarification or add additional context in comments.

Comments

2

Get the numeric index of key first using array_search() and array_keys(). Then slice the array from the beginning to key's index using array_slice()

$index = array_search($key, array_keys($array)); // Get the numeric index of search key
$result = array_slice($array, 0, $index, true);  // Slice from 0 up to index

print_r($result); // Print result

Comments

0

You can do this weird thing:

$key = 256;

$array = array(
    125 => array(571, 570), 
    284 => array(567, 566),
    256 => array(562, 560),
    110 => array(565, 563),
);

print_r(array_slice($array, array_search($key, array_keys($array)), null, true));

Outputs

Array
(
    [256] => Array
        (
            [0] => 562
            [1] => 560
        )

    [110] => Array
        (
            [0] => 565
            [1] => 563
        )

)

UPDATE

I realize now that I look again, I did it backwards. I call dyslexic moment... To do it the right way is like this

print_r(array_slice($array, 0, array_search($key, array_keys($array)),true));

Comments

0
$position = array_search($key, array_keys($array));
$output = array_slice($array, 0, $position);
print_r($output);

DEMO: https://3v4l.org/nmnDv

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.