We Rub Chan
We Rub Chan

Reputation: 205

Cannot put string into array in PHP

I try to put a string to $qDateTime and print it out. I expect the result is Array ( [0] => 2013-12-16 08:38:33 [1] => 2013-12-16 08:44:58 ). But it print Array ( [0] => 2013 [1] => 2013 ). And the $temp can print out correctly like 2013-12-16 08:38:332013-12-16 08:44:58.

    $qDateTime = array();

    $query = "SELECT joinDateTime FROM queueItem WHERE uid = '".$uid."' AND isValid = true;";
    $result = mysql_query($query) or die("Fail");
    while($array = mysql_fetch_array($result)){
        $temp = $array['joinDateTime'];
        $qDateTime[] += $temp;
        echo $temp;

    }
    print_r($qDateTime);

Upvotes: 0

Views: 70

Answers (3)

dev1234
dev1234

Reputation: 5716

The way of data assignment to array is incorrect. it should be,

$qDateTime[] = $temp; instead of $qDateTime[] += $temp;

print_r($qDateTime);

So the correct code must be,

  $qDateTime = array();

    $query = "SELECT joinDateTime FROM queueItem WHERE uid = '".$uid."' AND isValid = true;";
    $result = mysql_query($query) or die("Fail");
    while($array = mysql_fetch_array($result)){
        $temp = $array['joinDateTime'];
        $qDateTime[] = $temp;
        echo $temp;

    }
    print_r($qDateTime);

Upvotes: 0

Krish R
Krish R

Reputation: 22721

You should use $qDateTime[] = $temp; instead of $qDateTime[] += $temp;

    while($array = mysql_fetch_array($result)){
        $temp = $array['joinDateTime'];
        $qDateTime[] = $temp;
        echo $temp;

    }

    var_dump($qDateTime);

Upvotes: 0

andrewsi
andrewsi

Reputation: 10732

    $temp = $array['joinDateTime'];
    $qDateTime[] += $temp;
    echo $temp;

You're assigning data to the array wrongly:

    $qDateTime[] += $temp;

Should be:

    $qDateTime[] = $temp;

Because you're using += in your code, PHP is converting the date string to an integer, and using that for the result; so your 2013-12-16 08:38:332013-12-16 is becoming just 2013.

Upvotes: 3

Related Questions