开发者

PHP array problem

<?php
$d1 = '1';
$d2 = '1';
$d3 = '1';

$date2 = ''.$d1.','.$d2.','.$d3.'';

I want to to put these values in an array, but when I assign a variable as array($date2) it just gets prin开发者_JAVA百科ted as 'Array'.

What is the problem?

*Updated, this is the code that is printing 'Array':

$date2 = array($date);

echo $date2;


Firstly, you cannot just echo array('data');.

To put data into an array such as that, you need to specify it in the following format:

$array = array($d1,$d2,$d3); //build array
print_r($array); //show array contents
echo $array[0] //echo first array element

You can also add data to an array as follows:

// add to array
$array[] = 'item 1';
$array[] = 'item 2';

// add to array
array_push($array,'item 3');

Additional reading: foreach & arrays


Try this:

$date2 = array($d1, $d2, $d3);

That will create an array with those values.

If you want to view the contents of the array, do this:

var_dump($date2);


If you want to show what's in an array you can use var_dump or print_r. You can't use echo to view an array (unless you do it like Briedis describes).


Putting in the array:

$array['key'] = "Value";

Printing out:

echo "Array: " . $array['key'];


$date2[] = array();
$date2[0] = 10;
$date2[1] = 20;
$date2[2] = 30;


$date2 = array();
array_push($date2,$d1);
array_push($date2,$d2);
array_push($date2,$d3);// or one in all $date2 = array($var1,$var,$var3);
print_r($date2);

for printing array use print_r


you should define $date2 like this:

$date2 = ($d1,$d2,$d3);

the way you have it now, $date2 is just a string of concatenated values


As you wrote using

  print_r(array($date2));

will output Array ( [0] => 1,1,1 )

If you want add the three values separatly you should write this:

$date2 = array($d1, $d2, $d3);


Try the following code it will give you the expected output. There are three way print_r() , var_dump() and the ever green foreach(). you can use any of them.

<?php
$d1 = '1';
$d2 = '1';
$d3 = '1';

$date = ''.$d1.','.$d2.','.$d3.'';
$date2 = array($date);

echo "with print_r:";
print_r($date2);
echo "<hr/>";
echo "with var_dump:";
var_dump($date2);
echo "<hr/>";

echo "with foreach:<br/>";
foreach($date2 as $v)
    echo "$v<br/>";
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜