-4

Hi all basically I want to take a value from an array, modify it and then insert it as a new variable in the array. I kind of imagine it looking like follows but as I have never really worked with arrays I have no idea.

<?php
    $foobar = array(
        "foo" => "foo1",
        "bar" => "bar1",
    )

 $New_variable = "<img src="$foobar["foo"])">";

 $foobar[foo_img] = $New_variable;
 print_r $foobar;
?>

Hope that makes sense and thankyou in advance.

4

5 回答 5

3

Question is vague, but still try this,

$new_variable = "<img src=".$foobar['foo'].">";
$foobar['foo_img'] = $new_variable;
print_r($foobar);

Also you can directly do like this to save some lines of code,

$foobar['foo_img'] = "<img src=".$foobar['foo'].">";
于 2013-04-18T11:39:40.850 回答
1

You can do this in 2 steps

$foobar['foo_img'] = "<img src=" . $foobar['foo'] . ">";
print_r($foobar);
于 2013-04-18T11:41:31.743 回答
1

You don't even have to save it to a variable first. It's possible to change it directly in the array:

<?php
    $foobar = array(
        "foo" => "foo1",
        "bar" => "bar1"
    )

    $foobar["foo"] = "<img src='" . $foobar["foo"] . "'>";
    //                         ^  ^                ^  ^
    // Note concatenation using "." and the ''s 
    // to surround the string in the src attribute 
    print_r($foobar);
?>
于 2013-04-18T11:42:26.853 回答
1

There are syntax errors in your code.

Try this

$foobar = array(
        "foo" => "foo1",
        "bar" => "bar1"
);

$New_variable = "<img src='".$foobar['foo']."'>";

$foobar['foo_img'] = $New_variable;
print_r($foobar);
于 2013-04-18T11:43:15.283 回答
1

You don't need intermediate steps, and associative arrays are very easy to work with. The solution you're looking for is, directly, inserting the new variable without accounting for what's actually inside the existing array. You can do it like this:

$foobar["foo_img"] = "<img src=\"{$foobar["foo"]}\">";

As you can see, you don't even need to make a string separation. Hope that helps ;)

于 2013-04-18T11:55:03.800 回答