How to echo an array [duplicate] - php

This question already has answers here:
How can I echo or print an array in PHP?
(14 answers)
Closed 2 years ago.
It's not like I've never done it before, but for some reason it won't work this time... I'm just returnin an array from a function
//Call Function to create the result array
$specs = giveData();
and I'm trying to output the data with echo this way:
<b>lenght:</b><?php echo $specs[0]['lenght']; ?>
I already tried var_dump and it shows me the data in the array, also with print_r works.
EDIT: I updated the code the way it works for me.

Print all values of an array
<?php
echo '<pre>';
print_r($specs);
// OR var_dump to get variable type (string / int / etc)
var_dump($specs);
echo '</pre>';
?>
The echo of the pre tags are for formatting reasons in HTML since the pre tag will show linebreaks (\n) as a visible new line inside of HTML.
As for echoing a single value from an array, all you have to do is refernce the key like you were doing.
echo $specs['length'];
You can make sure the key exists by using the function isset.
if(isset($specs['length'])) {
echo $specs['length'];
}else{
echo 'Error, Length not found';
}
The functions used in this answer can be found on the PHP.net website var_dump(), print_r() and isset()

not sure if you want the number of elements of the array :
echo count($specs);
or iterate over your array :
foreach($specs as $key => $value){
echo "$key : $value<br/>";
}

Related

Cannot loop through items in JSON (php) [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i have the following Json sent via ajax to test.php:
[{},{"product[]":"john","qty[]":"12","price[]":"100","total[]":"1200"},{"product[]":"juan","qty[]":"22","price[]":"3.5","total[]":"77"},{"product[]":"louis","qty[]":"99","price[]":"1.22","total[]":"120.78"},{"product[]":"paul","qty[]":"5","price[]":"2.1","total[]":"10.5"},{"product[]":"carl","qty[]":"9","price[]":"14","total[]":"126"},{"total_amount":"1533.00"}]
In my php file I am trying to loop through each individual product[], qty[], price[] and list values:
<?php
$obj = json_decode($_POST["mydata"]);
header('Content-Type: application/json');
// echo json_encode($obj[1]->{'product[]'}); //(works)
foreach($obj as $item) {
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
?>
but this throws an error.
What is wrong in my loop?
There are a couple of things wrong with the code, the first is that you decode as objects and try and use this as an array. You need to pass true as the second parameter to json_decode() to make it an associative array.
The second is that your array contains elements which don't have all of the details. The last element only has "total_amount", so none of the other fields exist. This is why I use
if ( isset($item['product[]'])){
to check the object before outputting the data...
$obj = json_decode($_POST["mydata"], true);
header('Content-Type: application/json');
foreach($obj as $item) {
if ( isset($item['product[]'])){
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
}
Pass true as second argument to json_decode.
Per the documentation:
assoc
When TRUE, returned objects will be converted into associative arrays.
So your code becomes:
$obj = json_decode($_POST["mydata"], true);
Also note that the first entry in your array is empty, so you're gonna have to check for that.

How can i Iterate through data returned in Ajax success? [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
How can I iterate to get id value? This is my array:
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
tried
<?php
foreach($faculty as $value)
{
echo $value['Id'];
}
?>
Gives an error
Use of undefined constant Id - assumed Id
This is a json which is basically a string, to be more precise the given json contains a list (currently 1 element):
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
You need to convert it to an array first:
$jsonValues = json_decode($json, true); //here you will have an array of users (1 now)
foreach($jsonValues as $faculty) //for each user do something
{
echo $faculty['Id'];
}
This is JSON format. First you have to decode it. Example:
$a = '[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]';
$dec = json_decode($a);
echo $dec[0]->Id;
Result: 216
Decoded you have an array, containing exactly one object. You have to access the object properties with -> then.
With JSON [] brackets means an array, while {} brackets mean objects. Learn more: https://en.wikipedia.org/wiki/JSON

PHP: Get value from array? [duplicate]

This question already has answers here:
json_decode to array
(12 answers)
Closed 6 years ago.
I have a PHP variable that when I echo it will display an array that looks like this:
My Variable:
echo $mayVariable;
displays:
{"data":[{"id":"4756756575","name":"David","url":"https:\/\/www.somesite.com"}],"page":false}
I need to get the value from id within that array.
So I tried this:
echo $mayVariable[0]['id'];
But this doesn't give me anything.
I also tried:
echo $mayVariable['data']['id'];
and still I don't get anything in the echo...
Could someone please advise on this issue?
This JSON is an object array after decode it generally.
$json = '{"data":[{"id":"4756756575","name":"David","url":"https:\/\/www.somesite.com"}],"page":false}';
$arr = json_decode($json);
echo $arr->data[0]->id;//4756756575
If you use true as second parameter then:
$arr = json_decode($json, true);
echo $arr['data'][0]['id'];//4756756575

Array to string conversion in......array [duplicate]

This question already has answers here:
Display array values in PHP
(9 answers)
Closed 7 months ago.
I want to get the average of a column in a table,
table: buy
column: c1
when I called the database
with this:
$query="Select AVG(c1) as average FROM buy";
$result_array=mysql_query($query);
$line = mysql_fetch_array($result_array);
and when I called with php like this
<?php echo $line; ?>
it came up error with this message
Array to string conversion in .......... on line 50
Array
what did I do wrong? I think because I treated arrays as a string. but how can i fix this?
Please take a look that $line returns an array. So, you can't echo an array. One thing you can do is
echo "<pre>";
print_r($line);
Check what the array looks like.
Is it a single row that's been returned? In that case you can write
echo $line['average'];
If it's more than one row:
while ($line = mysql_fetch_array($result_array)) {
echo $line['average'];
}
Hope this helps.
Peace! xD

Passing multiple variable for php page

Hey guys I need help on passing multiple values for my PHP
http://s596.beta.photobucket.com/user/kingbookal/media/Capture.png.html?sort=3&o=0
That's the code from the 1st page and for the next page it is
$year = $_GET['yearlevel'];
I tried to alert the value but its null.
Please guide me well..
https://www.dropbox.com/sh/fokl2hnrjtpsfbn/Rcm8EfApm1
This is the link for my scripts
Do you want to echo the value from a key inside an array? Then you do like this:
echo $rowProfName['professor_name'];
If it doesn't return anything, you could check if a key exists in the array by using the following code:
if(!isset($rowProfName['professor_name']))
{
echo "Array key 'professor_name' is not set.";
}
If you want to check what your array contains, simply run this code:
$yourArray=array("value1","value2");
print_r($yourArray);
//If you want clean output as HTML, use this:
echo "<pre>";
print_r($yourArray);
echo "</pre>";
I hope I understood your question.

Categories