开发者

Accessing array elements using the associative index and numbered index

Is it possible to define an arra开发者_JS百科y where I can access the elements via their string and numeric index?


array_values() will return all values in an array with their indices replaced with numeric ones.

http://php.net/array-values

$x = array(
    'a' => 'x',
    'b' => 'y'
);
$x2 = array_values($x);

echo $x['a']; // 'x'
echo $x2[0]; // 'x'

The alternative is to build a set of by-reference indices.

function buildReferences(& $array) {
    $references = array();
    foreach ($array as $key => $value) {
        $references[] =& $array[$key];
    }
    $array = array_merge($references, $array);
}

$array = array(
    'x' => 'y',
    'z' => 'a'
);

buildReferences($array);

Note that this should only be done if you're not planning on adding or removing indices. You can edit them though.


You can do this.

$arr = array(1 => 'Numerical', 'two' => 'string');
echo $arr[1]; //Numerical
echo $arr['two']; //String


martswite's answer is correct, although if you've already got an associative array it may not solve your problem. The following is an ugly hack to work around this - and should be avoided at all cost:

$a = array(
'first' => 1,
'second' => 2,
'third' => 3
 );
 $b=array_values($a);

 print $b[2];


PHP allows a mixture of string and numeric-indexed elements.

$array = array(0=>'hello','abc'=>'world');

echo $array[0]; // returns 'hello'
echo $array['0']; // returns 'hello'
echo $array['abc']; // returns 'world';
echo $array[1]; // triggers a PHP notice: undefined offset

A closer look at the last item $array[1] reveals that it is not equivalent to the 2nd element of the array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜