简体   繁体   中英

Assign array key's value to another key of the same array PHP

Ok, so this is a super-newb question...

When creating an array, is there any way I could assign a key's value to another key in the same array?

For example:

<?php
$foobarr = array (
    0 => 'foo',
    1 => $foobarr[0] . 'bar',
);
?>

In this example $foobarr[1] holds the value 'bar'.

Any way I can do this so that $foobarr[1] == 'foobar' ?

No, you can't do that, because the array hasn't been constructed yet when you try to reference it with $foobarr[0] .

You could save 'foo' to another variable though, and just use that:

$foo = 'foo';
$foobarr = array (
    0 => $foo,
    1 => $foo . 'bar',
);

You can do it if you assign the keys individually:

$foobarr = array();
$foobarr[0] = 'foo';
$foobarr[1] = $foobarr[0] . 'bar';

etc. But not all at once inside the initializer - the array doesn't exist yet in there.

Sure, you'd need to reference it outside though.

$foobarr = array (
    0 => 'foo'
);
$foobarr[1] = $foobarr[0] . 'bar';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM