0

I'm trying to put a variable of an array in another element in the same array.

$list = array (
    array (
      "id"  =>  "9789045630816",
      "image"   =>  "<img src=\"images/" . array["id"] . ".png\">",
      "title"   =>  "Studio Webdesign"
    )
);

I'm trying to get "image" to hold <img src="images/9789045630816.png"> .

3
  • 1
    What do you exactly want? Its not clear. Commented Apr 23, 2014 at 9:52
  • Try this: <?php echo $list[0][image]; ?> Commented Apr 23, 2014 at 9:54
  • is your array dynamic , i mean it may contain alot of elements (images) inside ?? Commented Apr 23, 2014 at 9:57

3 Answers 3

3

It isn't clear why you can't just assign values to both array elements from a variable:

$id = '9789045630816';
$list = array(
  'id'    =>  $id,
  'image' =>  "<img src=\"images/$id.png\">",
  'title' =>  'Studio Webdesign'
);
Sign up to request clarification or add additional context in comments.

1 Comment

This. Whatever creates the original array's id element, should additionally create the image element.
1

You can do something like:

$list = array(
        array
        (
        "id"    =>  "9789045630816",
        "image" =>  "<img src=\"images/",
        "title" =>  "Studio Webdesign"
                    )
        );
$list[0]['image'].=$list[0]["id"] . ".png\">";

Comments

0

With static array declarations, you can't reference an element before the whole array is created.

I'm just brainstorming here, but to clean this up you could create a builder function instead:

function createItem($id, $title)
{
    return [
        'id' => $id,
        'image' => sprintf('<img src="images/%s.png" />', $id),
        'title' => $title,
    ];
}

And then:

$list = [createItem('9789045630816', 'Studio Webdesign')];

2 Comments

Of course, if one is going to create a function like that in order to create multiple such elements, then why not simply build the <img> tag using the value of the id element when needed? That is, why store the image element in the array at all?
It's a fool that looks for logic in the chambers of the human heart ;-)

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.