获取关键数据的最有效方法,即关联数组的两个键之间的值

i have an array

$var = array("one"=>"one","two"=>"two","three"=>"three","four"=>"four");

if i passed keys one,three i want to get values one , two ,three with keys .

now i am doing is

$new_array = array_diff(array_slice($var,$key1),array_slice($var,$key2));
$new_array[$key1] = $var[$key1];
$new_array[$key2] = $var[$key2];

is there any efficient way , please help .

Assuming your input array has contiguous keys, why not just:

$newArray = array_slice($array, $key1, $key2 + 1);

EDIT

Oh wait, that will only work when $key1 = 0, try this instead:

$newArray = array_slice($array, $key1, ($key2 - $key1) + 1);

This still requires that $key1 < $key2, but from what you say I imagine it always will be.

ANOTHER EDIT

In order to accomplish this without looping the array (with would of course be the easiest way) you need to convert the string keys to numerics so they can be used with array_slice(). This works:

$var = array("one"=>"one","two"=>"two","three"=>"three","four"=>"four");
$key1 = 'one';
$key2 = 'three';

$keys = array_keys($var);
$key1index = array_search($key1, $keys);
$key2index = array_search($key2, $keys);

$newArray = array_slice($var, $key1index, ($key2index - $key1index) + 1, TRUE);

print_r($newArray);

You pass in a key $from and a key $to. To have something from - to working, you need to know the order as well. You get the order of keys with array_keys:

$keys = array_flip(array_keys($array));

Now you can locate both the offset of $from and $to keys:

array_slice($array, $keys[$from], $keys[$to] - $keys[$from] + 1);

Compile as a full example:

<?php
/**
 * Most efficient way to get keys,values between two keys of an Associative array
 * @link http://stackoverflow.com/q/11358192/367456
 */

$array = array("one" => "one", "two" => "two", "three" => "three", "four" => "four");

$slice = function($from, $to) use ($array)
{
    $keys = array_flip(array_keys($array));
    if (isset($keys[$from]) and isset($keys[$to])) {
        return array_slice($array, $keys[$from], $keys[$to] - $keys[$from] + 1);
    }
    throw new InvalidArgumentException('Invalid from and/or to key.');
};

var_dump($slice('one', 'three'));

Output:

array(3) {
  ["one"]=>
  string(3) "one"
  ["two"]=>
  string(3) "two"
  ["three"]=>
  string(5) "three"
}