Jump to content

the way of output an array's result


runeveryday

Recommended Posts

how many ways that we can do to output an array's result,

eg:$row=array{...}

 

as far as i know,the followings are the output's format,which is right?and why?

 

echo $row[$key];

echo $row[key];

echo $row['key'];

i have tested the echo $row[$key]; is wrong, and what is the difference of the rest.thank you!

 

Link to comment
https://forums.phpfreaks.com/topic/167761-the-way-of-output-an-arrays-result/
Share on other sites

$row[$key] should work, IF $key represents an index number of the array or an associative key.

$row['key'] will work IF there is an associative key inside the array called key.

 

I've seen $row[key] being used, but I've never used it myself as I'm pretty sure that $row['key'] and $row[key] are the same thing.

I've seen $row[key] being used, but I've never used it myself as I'm pretty sure that $row['key'] and $row[key] are the same thing.

They're not.

'key' with the quotes is treated as a string value of 'key'

key (without the quotes) is treated as a constant called key, and PHP looks to the definition of this constant and uses that value. If no constant called key exists, then PHP will interpret it as a string with a value of 'key'.... and give you a Notice that it has done this.

 

error_reporting(E_ALL);
ini_set('display_errors', 1);

define('key','lock');

$test = array('key' => 1, 'lock' => 2);
$key = 'lock';

echo $test[$key].'<br />';
echo $test['key'].'<br />';
echo $test[key].'<br />';
echo $test[lock].'<br />';

Constants should be in all uppercase.
Again wrong.

Constants are normally all uppercase by convention rather than be necessity, but default behavious is case-sensitive. You can force them to be case insensitive with the optional third parameter for define().

 

error_reporting(E_ALL);
ini_set('display_errors', 1);

define('Constant1','Hello World');
define('Constant2','Hello Flowers',false);
define('Constant3','Hello Trees',true);

echo constant1.'<br />';
echo Constant1.'<br />';
echo CONSTANT1.'<br />';

echo constant2.'<br />';
echo Constant2.'<br />';
echo CONSTANT2.'<br />';

echo constant3.'<br />';
echo Constant3.'<br />';
echo CONSTANT3.'<br />';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.