1

How to position in one array thanks to one keys known, and to put in a variable all the keys which follow, the first key included ?

My key known : "r"

The key stop : "s"

My array :

['a'] => US
['r'] => UK
['v'] => DE
['s'] => IR     
['k'] => IT    
['o'] => AS

Result = r v

1
  • Your array is invalid. You can't have the 'r' index twice. Commented Jan 4, 2017 at 1:06

2 Answers 2

2

suppose you s key is behind r, here is the code:

Demo here

$keys = array_keys($array);
$flip_keys = array_flip($keys);
$result = array_slice($keys, $flip_keys['r'], $flip_keys['s'] - $flip_keys['r']);
Sign up to request clarification or add additional context in comments.

Comments

0

You have to parse the full array and check keys are inside the required bounds:

foreach( $theArray as $key => $value )
{
    if( $key >= 'r' && $key < 's' )
    {
        // will enter here with keys 'r' and 'v'

        $theArray[ $key ] = $theNewValue
    }
}

This assuming you want to catch all the values with keys that are alphabetically between "r" and "s" ("s" excluded).

This is not completely clear from your question.

Instead if you want to catch the values between "r" and "s" according to the array order then the codes changes slightly:

$update = false
foreach( $theArray as $key => $value )
{
    if( $key == 'r' )
    {
        $update = true;
    }
    elseif( $key == 's' )
    {
        break;
    }

    if( $update )
    {
        // will enter here with keys 'r' and 'v'

        $theArray[ $key ] = $theNewValue
    }
}

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.