Hey there! any question in your mind? Ask It Now!.

Popular Categories





How to print specific Array key in PHP?

+2 votes
303 views
asked in Programming by jatin Expert (3,823 points)

I have a function PHP getData which is returning some data on the basis of ID which we are passing in the function i.e   getData($ID);

Now printing data like :

$print = getData(323);

print_r($print );

 

Array ( [0] => Array ( [ID] => 323 [product] => samsung ))

 

When I am printing results on the basis of key so result is coming blank.


Please See and suggest : print_r($print[‘product’]);

3 Answers

+1 vote
answered by mannu (990 points)

Hi Jatin as you can see your result ,here are 2 different arrays

 

  1. Array having 0 index Array [0].

  2. Array having Index as ID Array [ID]=>323

 

So you have to print like this :

 

    

print_r($print[0] [‘product’]);

Now it would print 0 index of first array with index ID(323).

So you would get your results on the basis of specific array key.hope you got my point.

+1 vote
answered by amit_pammu Expert (5,030 points)
reshown by Bhartesh

Firstly, As i make out. You want to get the product info like it's name and ID.

1- if you want to fetch the product name it can be done by two method.

First - example:

$print = getData(323);

 

     by using array key so what you have to do just.

   print_r($print [0][product]);

output: samsung.

 

Second example  -

if you don't want to use the array key then just use any one loop. like see example below

foreach ($print as $print ):

echo $print [product];

endforeach;

output - samsung.

 

try this! may be you will get the point

 

 

 

0 votes
answered by Pascale Baerts

print_r is used to quickly output the content of an array abd shouldn't really be used to print a single value. Use print or echo instead. 
Your function getData() returns an array of arrays, and in your example it is an array containing just 1 array. It is that array that contains the keys you are trying to reach. 
Since it is an array in an array, you also need to define the key of the outer array which is 0. So to find the value from the 'product' key, you need to address $print[0]['product'] 

print($print[0]['product']);

Related Questions

+2 votes
1 answer 171 views
+4 votes
5 answers 756 views
+2 votes
1 answer 705 views
–1 vote
0 answers 145 views
0 votes
1 answer 9,887 views
+4 votes
1 answer 653 views
+6 votes
3 answers 7,003 views
+6 votes
2 answers 1,636 views
+2 votes
1 answer 122 views
+5 votes
1 answer 142 views
asked in Programming by jatin Expert (3,823 points)

Not a Member yet?

Ask to Folks Login

My Account
443 Folks are online
2 members and 441 guest online
Your feedback is highly appreciated