0

Is it possible to have an array assign its own element value to one of its other elements at the time you declare the array?

Here's a code example:

$arr = array ( 0 => '<ul class="'.$arr[1].'">', 1 => 'some_class' );

echo $arr[0]; // <ul class="some_class">

I've tried passing by reference (&$arr[1] instead of $arr[1] in the above code), but it gives a syntax error.

1
  • the $arr on the left side of the assignment won't exist until the right-hand side's been evaluated, and $arr[1] in the right-hand side can't exist until the right-hand side completes and gets assigned to the left-hand side. e.g. you're trying to count your chickens before chickens even existed. Commented Jul 2, 2013 at 21:54

2 Answers 2

1

You can do something along these lines

$arr = array ( '<ul class="%s">', 'some_class' );

and when you want to render just call

echo call_user_func_array("sprintf", $arr);
Sign up to request clarification or add additional context in comments.

3 Comments

Would that work if there were more that those 2 elements in the array?
as long the number of placeholder in the first parameter equals the number of elements in the array (minus 1 for the pattern itself) you are golden.
That's a really neat trick. It's not exactly what I was looking for, but it does fix my problem. Thank you.
1

No, you can't access an element of an array before the array has been declared. Just use another variable:

$class_name = 'some_class'
$arr = array ( 0 => '<ul class="'.$class_name.'">', 1 => $class_name );

echo $arr[0]; // <ul class="some_class">

You could also assign elements individually and refer to them in later assignments:

$arr = array();
$arr[1] = 'some_class';
$arr[0] = '<ul class="'.$arr[1].'">';

echo $arr[0]; // <ul class="some_class">

2 Comments

I want to make it so that if $arr[1] changes, $arr[0] will change as well. I'd also like avoid hard-coding "> at the end of something like echo $arr[0].$arr[1].'">' or creating another array element for ">, but those appear to be my only choices.
sounds like a job for a class with a getter/setter for the value, or a rethink of your design. (maybe you need to use more functions?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.