Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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'?

share|improve this question
5  
question is, why do you need to do it that way? –  Marko D Mar 13 '13 at 13:53
    
not like that no - the statement on the right of = is evaluated before it is assigned to $foobarr so within the array construct $foobarr doesn't exist yet. –  Emissary Mar 13 '13 at 13:53
    
What @MarkoD said. What's the problem that you're trying to solve? There's probably a way to solve it without this particular technical trick, which doesn't work in PHP. –  Mark Reed Mar 13 '13 at 13:54
1  
@NappingRabbit of course it doesn't work, and final comma in array is not a problem –  Marko D Mar 13 '13 at 13:56
    
$foobarr[] = "foo"; $foobarr[] = $foobarr[0]."bar"; –  jdstankosky Mar 13 '13 at 13:57
add comment

3 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment

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',
);
share|improve this answer
    
+ this is much more readable. –  dfsq Mar 13 '13 at 13:55
add comment

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

$foobarr = array (
    0 => 'foo'
);
$foobarr[1] = $foobarr[0] . 'bar';
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.