printing array by foreach loop in php - php

Can I print all of the elements of an array in one go in foreach loop ?
I tried this but dont understand this list fully.
foreach ($array as list ($a,$b,$c,$d,$e))
{
echo "<td>".$a."</td>";
echo "<td>".$b."</td>";
echo "<td>".$c."</td>";
echo "<td>".$d."</td>";
echo "<td>".$e."</td>";
}
Thank you.
here is the sample of array
Array ( [0] => sajan sahoo [1] => PHP [2] => JS [3] => JQ [4] => Mysql )

it is rather:
list($a,$b,$c,$d,$e) = $array;
echo "<td>".$a."</td>";
echo "<td>".$b."</td>";
echo "<td>".$c."</td>";
echo "<td>".$d."</td>";
echo "<td>".$e."</td>";
Or:
$output = "<td>";
$output .= implode("</td><td>",$array);
$output .= "</td>";
echo $output;

If you are dealing with a multidimensional array ( by the look of the 'foreach( $array...' t looks like you are, then perhaps something like the following? You will see that the variables $a,$b etc have been replaced with strings in the example
$array=array(
array('one','two','three','four','five'),
array('six','seven','eight','nine','ten'));
function td( &$item, $key ){
echo '<td>'.$item.'</td>';
}
array_walk_recursive( $array,'td');

For your sample array,
$arr = Array ( [0] => sajan sahoo [1] => PHP [2] => JS [3] => JQ [4] => Mysql );
If you want to print all array at once you can do just by echoing array key as,
echo "<td>".$arr[0]."</td>";
echo "<td>".$arr[1]."</td>";
echo "<td>".$arr[2]."</td>";
echo "<td>".$arr[3]."</td>";
echo "<td>".$arr[4]."</td>";
in that case why you need foreach loop.
But if you meant about nested loop then in PHP 5.5 you can do so by using list with foreach as
$array = [
[1, 2],
[3, 4],
];
foreach ($array as list($a, $b)) {
// $a contains the first element of the nested array,
// and $b contains the second element.
echo "A: $a; B: $b\n";
}
then it will output as
A: 1; B: 2
A: 3; B: 4
Refer the PHP official manual for more information.

Use var_dump(): http://php.net/manual/en/function.var-dump.php
void var_dump ( mixed $expression [, mixed $... ] )
This function displays structured information about one or more
expressions that includes its type and value. Arrays and objects are
explored recursively with values indented to show structure.
Also interesting:
Keep in mind if you have xdebug installed it will limit the var_dump()
output of array elements and object properties to 3 levels deep.
To change the default, edit your xdebug.ini file and add the
folllowing line: xdebug.var_display_max_depth=n
More information here: http://www.xdebug.org/docs/display

Related

How do i output an Array in PHP with JSON data in it? [duplicate]

I have this array
Array
(
[data] => Array
(
[0] => Array
(
[page_id] => 204725966262837
[type] => WEBSITE
)
[1] => Array
(
[page_id] => 163703342377960
[type] => COMMUNITY
)
)
)
How can I just echo the content without this structure?
I tried
foreach ($results as $result) {
echo $result->type;
echo "<br>";
}
To see the contents of array you can use:
print_r($array); or if you want nicely formatted array then:
echo '<pre>'; print_r($array); echo '</pre>';
Use var_dump($array) to get more information of the content in the array like the datatype and length.
You can loop the array using php's foreach(); and get the desired output. More info on foreach is in PHP's documentation website: foreach
This will do
foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}
If you just want to know the content without a format (e.g., for debugging purposes) I use this:
echo json_encode($anArray);
This will show it as a JSON which is pretty human-readable.
There are multiple functions for printing array content that each has features.
print_r()
Prints human-readable information about a variable.
$arr = ["a", "b", "c"];
echo "<pre>";
print_r($arr);
echo "</pre>";
Array
(
[0] => a
[1] => b
[2] => c
)
var_dump()
Displays structured information about expressions that includes its type and value.
echo "<pre>";
var_dump($arr);
echo "</pre>";
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
var_export()
Displays structured information about the given variable that returned representation is valid PHP code.
echo "<pre>";
var_export($arr);
echo "</pre>";
array (
0 => 'a',
1 => 'b',
2 => 'c',
)
Note that because the browser condenses multiple whitespace characters (including newlines) to a single space (answer), you need to wrap above functions in <pre></pre> to display result in thee correct format.
Also, there is another way to print array content with certain conditions.
echo
Output one or more strings. So if you want to print array content using echo, you need to loop through the array and in the loop use echo to print array items.
foreach ($arr as $key=>$item){
echo "$key => $item <br>";
}
0 => a
1 => b
2 => c
You can use print_r, var_dump and var_export functions of PHP:
print_r: Convert into human-readable form
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
var_dump(): will show you the type of the thing as well as what's in it.
var_dump($results);
foreach loop: using a for each loop, you can iterate each and every value of an array.
foreach($results['data'] as $result) {
echo $result['type'] . '<br>';
}
Try using print_r to print it in human-readable form.
foreach($results['data'] as $result) {
echo $result['type'], '<br />';
}
or echo $results['data'][1]['type'];
You don’t have any need to use a for loop to see the data into the array. You can simply do it in the following manner:
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
Human-readable (for example, can be logged to a text file...):
print_r($arr_name, TRUE);
You can use var_dump() function to display structured information about variables/expressions, including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.
Example: Say we have got the following array, and we want to display its contents.
$arr = array ('xyz', false, true, 99, array('50'));
print_r() function - Displays human-readable output
Array
(
[0] => xyz
[1] =>
[2] => 1
[3] => 99
[4] => Array
(
[0] => 50
)
)
var_dump() function - Displays values and types
array(5) {
[0]=>
string(3) "xyz"
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
int(100)
[4]=>
array(1) {
[0]=>
string(2) "50"
}
}
The functions used in this answer can be found on the PHP documentation website, var_dump() and print_r().
For more details:
How to display PHP variable values with echo, print_r, and var_dump
How can I echo an array in PHP?
If you want a parsable PHP representation, you could use:
$parseablePhpCode = var_export($yourVariable,true);
If you echo the exported code to a file.php (with a return statement) you may require it as
$yourVariable = require('file.php');
I checked the answers, however, (for each) in PHP it is deprecated and no longer works with the latest PHP versions.
Usually, we would convert an array into a string to log it somewhere, perhaps debugging, test, etc.
I would convert the array into a string by doing:
$Output = implode(",", $SourceArray);
Whereas:
$output is the result (where the string would be generated
",": is the separator (between each array field).
$SourceArray: is your source array.
If you only need echo 'type' field, you can use function 'array_column' like:
$arr = $your_array;
echo var_dump(array_column($arr['data'], 'type'));
Loop through and print all the values of an associative array, You could use a foreach loop, like this:
foreach($results as $x => $value) {
echo $value;
}

How to output different levels of an array

As a newbie, does anyone have any good tutorials to help me understand different levels of an array? What I'm trying to learn is how to echo different levels, e.g. here is the output array:
Array
(
[meta] =>
Array
(
[total_record_count] => 1
[total_pages] => 1
[current_page] => 1
[per_page] => 1
)
[companies] =>
Array
(
[0] =>
Array
(
[id] => 291869
[url] => https://api.mattermark.com/companies/291869
[company_name] => gohenry.co.uk
[domain] => gohenry.co.uk
)
)
[total_companies] => 1
[page] => 1
[per_page] => 1
)
And here is the code to parse the array:
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
I'm really struggling to find the structure and how to output each items, e.g. tried things like:
echo $item[0]['total_companies'];
echo $item['companies'][0]['id'];
Any help or pointers would be greatly received.
Well, Lets start, You have a multi-dimensional array. For a multi-dimensional array you need to use looping e.g: for, while, foreach. For your purpose it is foreach.
Start with the array dimension, Array can be multi-dimension, Like you have multi-dimension. If you have an array like below, then it is single dimension.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Now, How can you know what is a multi-dimension array, If you array has another array as child then it is called multi-dimensional array, like below.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
Its time to work with your array. Suppose you want to access the value of company_name, what should you do?? Let your array name is $arr.
First you need to use a foreach loop like:
foreach($arr as $key => $val)
The keys are (meta, companies, total_companies...), they are in the first dimension. Now check if the key is company_name or not, if it matches than you got it. Or else you need to make another loop if the $val is an array, You can check it using is_array.
By the same processing at the last element your loop executes and find your value.
Learning
Always a good idea to start with the docs:
arrays: http://php.net/manual/en/language.types.array.php
foreach: http://php.net/manual/en/control-structures.foreach.php
As for tutorials, try the interactive tutorial over at codecademy: https://www.codecademy.com/learn/php
Unit 4 has a tutorial on arrays
Unit 11 has a lesson on advanced arrays.
Your code
As for your code, look at the following which I will show you your array structure and how to access each element. Perhaps that will make things clearer for you.
So lets say your array is named $myArray, see how to access each part via the comments. Keep in mind this is not php code, I'm just showing you how to access the array's different elements.
$myArray = Array
(
// $myArray['meta']
[meta] => Array (
// $myArray['meta']['total_record_count']
[total_record_count] => 1
// $myArray['meta']['total_pages']
[total_pages] => 1
// $myArray['meta']['current_page']
[current_page] => 1
// $myArray['meta']['per_page']
[per_page] => 1
)
// $myArray['companies']
[companies] => Array (
// $myArray['companies'][0]
[0] => Array (
// $myArray['companies'][0]['id']
[id] => 291869
// $myArray['companies'][0]['url']
[url] => https://api.mattermark.com/companies/291869
// $myArray['companies'][0]['company_name']
[company_name] => gohenry.co.uk
// $myArray['companies'][0]['domain']
[domain] => gohenry.co.uk
)
)
// $myArray['total_companies']
[total_companies] => 1
// $myArray['page']
[page] => 1
// $myArray['per_page']
[per_page] => 1
)
As for your for each loop
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
What the foreach loop is doing is looping through each first level of the array $jsonObj, so that would include:
meta
companies
total_companies
page
per_page
Then within the curly braces {} of the foreach loop you can refer to each level by the variable $item.
So depending on what you want to achieve you need to perhaps change your code, what is it you're trying to do as it's not really clear to me.
As for the code within the loop:
echo $item['total_companies'];
It won't work because you're trying to access an array with the index of total_companies within the first level of the $jsonObj array which doesn't exist. For it to work your array would have to look like this:
$jsonObj = array (
'0' => array ( // this is what is reference to as $item
'total_companies' => 'some value'
)
)
What you want to do is this:
foreach($jsonObj as $item)
{
echo $jsonObj['total_companies'];
}
As for your final snippet of code:
echo $item[0]['total_companies'];
Answered this above. Access it like $jsonObj['total_companies'];
echo $item['companies'][0]['id'];
If you want to loop through the companies try this:
foreach($jsonObj['companies'] as $item)
{
// now item will represent each iterable element in $jsonObj['companies]
// so we could do this:
echo $item['id'];
}
I hope that all helps! If you don't understand please make a comment and I'll update my answer.
Please take a look in to here and here
Information about php arrays
Try recursive array printing using this function:
function recursive($array){
foreach($array as $key => $value){
//If $value is an array.
if(is_array($value)){
//We need to loop through it.
recursive($value);
} else{
//It is not an array, so print it out.
echo $value, '<br>';
}
}
}
if you know how deep your array structure you can perform nested foreach loop and before every loop you have to check is_array($array_variable), like :
foreach($parent as $son)
{
if(is_array($son))
{
foreach($son as $grandson)
{
if(is_array($son))
{
foreach($grandson as $grandgrandson)
{
.....
......
.......
}
else
echo $grandson;
}
else
echo $parent;
}
else
echo $son;
}
hope it will help you to understand

How can I echo or print an array in PHP?

I have this array
Array
(
[data] => Array
(
[0] => Array
(
[page_id] => 204725966262837
[type] => WEBSITE
)
[1] => Array
(
[page_id] => 163703342377960
[type] => COMMUNITY
)
)
)
How can I just echo the content without this structure?
I tried
foreach ($results as $result) {
echo $result->type;
echo "<br>";
}
To see the contents of array you can use:
print_r($array); or if you want nicely formatted array then:
echo '<pre>'; print_r($array); echo '</pre>';
Use var_dump($array) to get more information of the content in the array like the datatype and length.
You can loop the array using php's foreach(); and get the desired output. More info on foreach is in PHP's documentation website: foreach
This will do
foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}
If you just want to know the content without a format (e.g., for debugging purposes) I use this:
echo json_encode($anArray);
This will show it as a JSON which is pretty human-readable.
There are multiple functions for printing array content that each has features.
print_r()
Prints human-readable information about a variable.
$arr = ["a", "b", "c"];
echo "<pre>";
print_r($arr);
echo "</pre>";
Array
(
[0] => a
[1] => b
[2] => c
)
var_dump()
Displays structured information about expressions that includes its type and value.
echo "<pre>";
var_dump($arr);
echo "</pre>";
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
var_export()
Displays structured information about the given variable that returned representation is valid PHP code.
echo "<pre>";
var_export($arr);
echo "</pre>";
array (
0 => 'a',
1 => 'b',
2 => 'c',
)
Note that because the browser condenses multiple whitespace characters (including newlines) to a single space (answer), you need to wrap above functions in <pre></pre> to display result in thee correct format.
Also, there is another way to print array content with certain conditions.
echo
Output one or more strings. So if you want to print array content using echo, you need to loop through the array and in the loop use echo to print array items.
foreach ($arr as $key=>$item){
echo "$key => $item <br>";
}
0 => a
1 => b
2 => c
You can use print_r, var_dump and var_export functions of PHP:
print_r: Convert into human-readable form
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
var_dump(): will show you the type of the thing as well as what's in it.
var_dump($results);
foreach loop: using a for each loop, you can iterate each and every value of an array.
foreach($results['data'] as $result) {
echo $result['type'] . '<br>';
}
Try using print_r to print it in human-readable form.
foreach($results['data'] as $result) {
echo $result['type'], '<br />';
}
or echo $results['data'][1]['type'];
You don’t have any need to use a for loop to see the data into the array. You can simply do it in the following manner:
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
Human-readable (for example, can be logged to a text file...):
print_r($arr_name, TRUE);
You can use var_dump() function to display structured information about variables/expressions, including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.
Example: Say we have got the following array, and we want to display its contents.
$arr = array ('xyz', false, true, 99, array('50'));
print_r() function - Displays human-readable output
Array
(
[0] => xyz
[1] =>
[2] => 1
[3] => 99
[4] => Array
(
[0] => 50
)
)
var_dump() function - Displays values and types
array(5) {
[0]=>
string(3) "xyz"
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
int(100)
[4]=>
array(1) {
[0]=>
string(2) "50"
}
}
The functions used in this answer can be found on the PHP documentation website, var_dump() and print_r().
For more details:
How to display PHP variable values with echo, print_r, and var_dump
How can I echo an array in PHP?
If you want a parsable PHP representation, you could use:
$parseablePhpCode = var_export($yourVariable,true);
If you echo the exported code to a file.php (with a return statement) you may require it as
$yourVariable = require('file.php');
I checked the answers, however, (for each) in PHP it is deprecated and no longer works with the latest PHP versions.
Usually, we would convert an array into a string to log it somewhere, perhaps debugging, test, etc.
I would convert the array into a string by doing:
$Output = implode(",", $SourceArray);
Whereas:
$output is the result (where the string would be generated
",": is the separator (between each array field).
$SourceArray: is your source array.
If you only need echo 'type' field, you can use function 'array_column' like:
$arr = $your_array;
echo var_dump(array_column($arr['data'], 'type'));
Loop through and print all the values of an associative array, You could use a foreach loop, like this:
foreach($results as $x => $value) {
echo $value;
}

php array variable

in my script,
$value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
if(in_array("Bloomsberry",$value)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}
this works well
i have a variable $names which is a mysql result, which has data "DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer" like an array data.
but when i place the variable inside like $value= array($names); instead of $value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"); , i am getting result "Bloomsberry is not there " instead of expected "Bloomsberry is there inside the array"
I suspect that the " signs get escaped and that also the array is passed as an single string. You will have to split the string to an array. If I where you I would submit to mysql: "DK,Bloomsberry,McGrawHill"etc and then do
<?php
$string = "DK,Bloomsberry,McGrawHill,OXFORD,DC Books,Springer";
$array = explode(",", $string);
if(in_array("Bloomsberry",$array)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}
The explode command returns an array split on the commas.
I hope this works for you
If $names is already an Array, then array($names) is an Array containing one element (the one element is your $names array).
If you want to assign $value to the array $names, you simply use the assignment operator:
$value = $names;
Then do your conditional in_array("Bloomsberry", $value);. Or you could just avoid the assignment and do in_array("Bloomsberry", $names).
Notice the following difference:
$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
print_r($value);
/* produces:
Array
(
[0] => DK
[1] => Bloomsberry
[2] => McGrawHill
[3] => OXFORD
[4] => DC Books
[5] => Springer
)
*/
where as:
$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
$newValue = array($value);
print_r($newValue );
/* produces:
Array
(
[0] => Array
(
[0] => DK
[1] => Bloomsberry
[2] => McGrawHill
[3] => OXFORD
[4] => DC Books
[5] => Springer
)
)
*/
in_array("Bloomsberry", $newValue) will only return true if "Bloomsberry" is a value in the first dimension of the array. However the only first dimension element in $newValue is the $value array.
Issue:
This is because in_array starts checking at the root node, and depending on how many levels the needle has depends in how many levels it checks within the haystack
An example of the above:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a))
{
echo "'ph' was found\n";
}
$a is actually 2 levels of arrays, also called multi-dimensional.
Within your code your placing your root level array, into another array, thus the array of the DB Then becomes array(array("results")) this when you check the first node using in_array("string") it cant find it within the root haystack.
Possible Fix:
Just use the actual result as your in_array check, example:
while($row = mysql_fetch_array($result))
{
/*
$row is a single dimension and can be used like so:
*/
if(in_array("Bloomsberry"),$row))
{
//Echo your success.
}
}
try this
$name = '"DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"';
$name = str_replace('"', '', $name);
$value = explode(',', $name);
Now your below given code will work.
if(in_array("Bloomsberry",$value)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}

Echo a multidimensional array in PHP

I have a multidimensional array and I'm trying to find out how to simply "echo" the elements of the array. The depth of the array is not known, so it could be deeply nested.
In the case of the array below, the right order to echo would be:
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
This is the array I was talking about:
Array
(
[0] => Array
(
[comment_id] => 1
[comment_content] => This is a parent comment
[child] => Array
(
[0] => Array
(
[comment_id] => 3
[comment_content] => This is a child comment
[child] => Array
(
[0] => Array
(
[comment_id] => 4
[comment_content] => This is the 2nd child comment
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[comment_id] => 2
[comment_content] => This is another parent comment
[child] => Array
(
)
)
)
<pre>
<?php print_r ($array); ?>
</pre>
It looks like you're only trying to write one important value from each array. Try a recursive function like so:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
You could also make it a little more dynamic and have the 'comment_content' and 'child' strings passed into the function as parameters (and continue passing them in the recursive call).
Proper, Better, and Clean Solution:
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach ($array as $key => $value)
{
if (is_array($value))
{
Self::traverseArray($value); // Or
// traverseArray($value);
}
else
{
echo $key . " = " . $value . "<br />\n";
}
}
}
You simply call in this helper function traverseArray($array) in your current/main class like this:
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);
source: http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/
print_r($arr) usually gives pretty readable result.
if you wanted to store it as a variable you could do:
recurse_array($values){
$content = '';
if( is_array($values) ){
foreach($values as $key => $value){
if( is_array($value) ){
$content.="$key<br />".recurse_array($value);
}else{
$content.="$key = $value<br />";
}
}
}
return $content;
}
$array_text = recurse_array($array);
Obviously you can format as needed!
There are multiple ways to do that
1) - print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
//-------------------------------------------------
2) - use var_dump($array) to get more information of the content in the array like datatype and length.
//-------------------------------------------------
3) - you can loop the array using php's foreach(); and get the desired output.
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['child']);
}
}
Try to use var_dump function.
If you're outputting the data for debugging and development purposes, Krumo is great for producing easily readable output. Check out the example output.
Recursion would be your answer typically, but an alternative would be to use references. See http://www.ideashower.com/our_solutions/create-a-parent-child-array-structure-in-one-pass/

Categories