Reputation: 31
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
Upvotes: 1
Views: 36
Reputation: 28529
suppose you s key is behind r, here is the code:
$keys = array_keys($array);
$flip_keys = array_flip($keys);
$result = array_slice($keys, $flip_keys['r'], $flip_keys['s'] - $flip_keys['r']);
Upvotes: 2
Reputation: 15827
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
}
}
Upvotes: 0