How can I echo or print an array in PHP? - 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;
}

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 get value in an object in PHP

I have a variable with object like this in PHP code.
[{"author_id":2},{"author_id":1}]
How to get the value of author_id. thanks
use json_decode to convert the object in php and get it. Example:
<?php
$xx='[{"author_id":2},{"author_id":1}]';
$arr=json_decode($xx,true);
print_r($arr);
//Output: Array ( [0] => Array ( [author_id] => 2 ) [1] => Array ( [author_id] => 1 ) )
echo $arr[0]["author_id"];
//Outpu: 2
?>
This is serialized JSON Array with JSON objects inside.
$str = '[{"author_id":2},{"author_id":1}]';
$arr = json_decode($str, true);
foreach($arr as $item) {
echo $item['author_id'];
}
That data you posted is in JSON format. After decoding that standard format you can directly access the contents.
For the first entry that would simply be:
<?php
$data = json_decode('[{"author_id":2},{"author_id":1}]');
var_dump($data[0]->author_id);
The output obviously is:
int(2)
To access all entries have a try like that:
The output then is:
array(2) {
[0]=>
int(2)
[1]=>
int(1)
}

Get array out of a Json?

I am getting a Json respond with :
$response = curl_exec($rest);
$json = json_decode($response, true);
I manage to get its values(strings) with :
$foundUserId=$json['results'][0]['userId'];
$foundName=$json['results'][0]['name'];
$foundPhoneNum=$json['results'][0]['phoneNumber'];
But the last value- phoneNumber, is array of strings .
If i try then to loop over it i get nothing(although the array is there in the Json)
foreach ($foundPhoneNum as &$value)
{
print_r($value);
}
What am i doing wrong ?
EDIT :
The json:
Array ( [results] => Array ( [0] => Array ( [action] => message [createdAt] => 2015-11-21T09:36:33.620Z [deviceId] => E18DDFEC-C3C9 [name] => me [objectId] => klMchCkIDi [phoneNumber] => ["xx665542","xxx9446"] [state] => 1 [updatedAt] => 2015-11-22T08:24:46.948Z [userId] => 433011AC-228A-4931-8700-4D050FA18FC1 ) ) )
You might have json as a string inside json. That's why after json_decode() you still have json inside phoneNumber. You have 2 options:
Decode phoneNumber like
$foundPhoneNum=json_decode($json['results'][0]['phoneNumber']);
Build proper initial json. Instead of
{"phoneNumber": "[\"xx665542\",\"xxx9446\"]"}
should be
{"phoneNumber": ["xx665542","xxx9446"]}
There's a couple of ways to debug situations like this as mentioned in the comments; print_r() and var_dump().
var_dump(), although harder to read the first few times, is my favourite because it tells you the data types of each value in the array. This will confirm whether or not the expected string is indeed an array.
An example from the var_dump() documentation:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
And the output is;
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
As you can see it shows array, int and string as the data types.
You might also like to install the Xdebug extension for PHP which dumps more useful error messages and tracebacks. Again harder to read the first few times, but well worth it!
foreach ($foundPhoneNum as $value)
{
print_r($value);
}
There was an extra & before $value. Try this.

printing array by foreach loop in 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

How do you remove a value that has an empty key from an associative array in PHP?

I have a key that appears to be an empty string, however using unset($array[""]); does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.
The line for the element on a print_r is [] => 1, which indicates to me that the key is the empty string.
Using var_export, the element is listed as '' => 1.
Using var_dump, the element is listed as [""]=>int(1).
So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried unset($array[""]);, unset($array['']);, and unset($array[null]); with no luck.
Try unset($array[null]);
If that doesn't work, print the array via var_export or var_dump instead of print_r, since this allows you to see the type of the key. Use var_export to see the data in PHP syntax.
var_export($array);
Note that var_export does not work with recursive structures.
Tried:
$someList = Array('A' => 'Foo', 'B' => 'Bar', '' => 'Bah');
print_r($someList);
echo '<br/>';
unset($someList['A']);
print_r($someList);
echo '<br/>';
unset($someList['']);
print_r($someList);
echo '<br/>';
Got:
Array ( [A] => Foo [B] => Bar [] => Bah )
Array ( [B] => Bar [] => Bah )
Array ( [B] => Bar )
You should analyse where the key come from, too...
My guess is that it's not an empty string. Try the following to see what you get:
foreach ($array as $index => $value) {
echo $index;
echo ' is ';
echo gettype($index);
echo "\n";
}
Try using var_dump instead of print_r. This may give you a better idea of what exactly the key is.
Not sure what to tell you. Running this script
<?php
$arr = array(
false => 1
, true => 2
, null => 3
, 'test' => 4
// , '' => 5
);
print_r( $arr );
foreach ( $arr as $key => $value )
{
var_dump( $key );
}
unset( $arr[''] );
print_r( $arr );
I get the following output
Array
(
[0] => 1
[1] => 2
[] => 3
[test] => 4
)
int(0)
int(1)
string(0) ""
string(4) "test"
Array
(
[0] => 1
[1] => 2
[test] => 4
)
See how the "null" array key was type converted to an empty string?
Are you sure you are not working with a copy of the array? If you did this call to unset() from inside a function, it's possible that you are.
This was tested on PHP 5.2.0
Please post the code you use to remove the element as well your checker code before and after that line.
What I'm looking for is something like this:
var_export($array);
echo "\n";
unset($array[""]);
var_export($array);
Please also post the complete output of both var_export lines.
I'm looking for something like this:
array (
'' => 1,
)
array (
)

Categories