0

Why does this not work?

    $w = '"one","two"';
    $a = array($w);
    for($i = 0; $i < count($a); $i++) {
        echo $a[$i].'<br />';
        }

The one above outputes: "one","two"

But This does?

    $a = array("one","two");
    for($i = 0; $i < count($a); $i++) {
        echo $a[$i].'<br />';
        }

The one above outputs:

one
two

This has to be dynamically pulled from a database. I'm storing the info as an array with quotes around each element. So, when I want to pull the data I'm just going to throw a variable for that row in an array. But, since that isn't working how do I make it work? Thank you

1
  • could you do $a = array(eval($w));? Commented Mar 14, 2012 at 1:48

3 Answers 3

2
$w = '"one","two"';
$a = array($w);

Creates an array with one element "one","two" (check with var_dump($a);)

$a = array("one","two");

Creates an array with two elements "one" and "two"

If the data comes from the database as a string of comma-separated items, you could split them with explode(), but it is a terrible practice - you shouldn't store multiple values in a string.

Sign up to request clarification or add additional context in comments.

Comments

0

In the first example, you are building an array with a single string "one","two".

In the second example, you are building an array with two strings: "one" and "two".

If you have a string like in example 1 that you want to turn into an array, you can use the php function explode(): http://php.net/manual/en/function.explode.php

Comments

0

All I can say is that the first method is outputting a string literal. Perhaps php doesn't doesn't understand how many items to put in your array... Anyhow, you might try loading the strings "One" and "Two" into the array one at a time rather than at the point of declaration. :/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.