Let's pretend you have a PHP array like the one below called
"myArray", or any array for that matter that you wish to show both keys
and values for in order to debug a scriipt or whatever purpose you have
in mind.
First to be thorough, I'll show you quickly how to make a PHP array.
The first code example below demonstrates an array's structure. The
second is the actual "myArray" array we use in the rest of the code
samples on this page.
'key_1' => 'value_1',
'key_2' => 'value_2',
'key_3' => 'value_3'
);
'firstname' => 'Ian',
'lastname' => 'Lin',
'password' => '1234'
);
Okay, good, now we have an array and if you didn't know how to make a PHP array, now you do! Let's say we want to show the contents of that array in our script so we can be sure it's working. Here are two methods that will show both keys and values stored in a PHP array. Each code example in green is followed by sample output in orange.
PHP Code to Show Keys and Values of an Array:
Example #1:
foreach($myArray as $key=>$val){
echo "<p style='color:orange'>$key) $val</p>";
}//end foreach
Output:
firstname) Ian
lastname) Lin
password) 1234
Example #2:
echo "<hr /><pre>";
print_r($postarray);
echo "</pre>";
Output:
Array
(
[firstname] => Ian
[lastname] => Lin
[password] => 1234
)
Structure of a PHP Array
array_name = array('key_1' => 'value_1',
'key_2' => 'value_2',
'key_3' => 'value_3'
);
Example PHP Array:
myArray = array('firstname' => 'Ian',
'lastname' => 'Lin',
'password' => '1234'
);
Okay, good, now we have an array and if you didn't know how to make a PHP array, now you do! Let's say we want to show the contents of that array in our script so we can be sure it's working. Here are two methods that will show both keys and values stored in a PHP array. Each code example in green is followed by sample output in orange.
PHP Code to Show Keys and Values of an Array:
Example #1:
foreach($myArray as $key=>$val){
echo "<p style='color:orange'>$key) $val</p>";
}//end foreach
Output:
firstname) Ian
lastname) Lin
password) 1234
Example #2:
echo "<hr /><pre>";
print_r($postarray);
echo "</pre>";
Output:
Array
(
[firstname] => Ian
[lastname] => Lin
[password] => 1234
)
0 comments:
Post a Comment