Jump to content

Data from Array inside a Function - Help!


John_A

Recommended Posts

I thought this would be fairly straightforward but for some reason isn't working.

 

I have an array built from some MySQL data: -

 

$all_products[1] = array(
"title"=>"widget",
"product_code"=>"wid-123",
"colour"=>"blue");  

$all_products[2] = array(
"title"=>"thingy",
"product_code"=>"thi-345",
"colour"=>"red"); 

 

This works fine when used like: -

 

echo 'Product #1 is a ' . $all_products[1]['colour'] . $all_products[1]['title'] . ', code: ' . $all_products[1]['code'];

 

Gives: "Product #1 is a blue widget, code: wid-123"

 

However, if I do this: -

 

function showproductinfo($thisproduct)
{
echo 'Product #' . $thisproduct . ' is a ' . $all_products[$thisproduct]['colour'] . $all_products[$thisproduct]['title'] . ', code: ' . $all_products[$thisproduct]['code'];
}

showproductinfo(1);

 

It gives nothing :(

 

Can I use a variable passed via a function as the array key in this way? If so, how? And if not, what's the best way to do what I, trying to do?

Link to comment
https://forums.phpfreaks.com/topic/227870-data-from-array-inside-a-function-help/
Share on other sites

Thanks both for your help!

 

I did this: -

 

function showproductinfo($thisproduct){
global $all_products;
echo 'Product #' . $thisproduct . ' is a ' . $all_products[$thisproduct]['colour'] . $all_products[$thisproduct]['title'] . ', code: ' . $all_products[$thisproduct]['code'];
}

showproductinfo(1);

 

Which seems to work. Are there any downsides to this?

If $all_products[$thisproduct] contains the product ID, just pass that.

 

If $all_products[$thisproduct] does not contain the product ID, pass the product ID along with $all_products[$thisproduct].

 

Do not pass the whole array every time if all you're going to be doing is sucking out a single product.

 

-Dan

beter pass index and part of array

 

If $all_products[$thisproduct] contains the product ID, just pass that.

 

If $all_products[$thisproduct] does not contain the product ID, pass the product ID along with $all_products[$thisproduct].

 

Do not pass the whole array every time if all you're going to be doing is sucking out a single product.

 

Thanks for your help! I ended up with this which works great: -

 

function showproductinfo($thisproduct){
echo 'Product #' . $thisproduct['product_id'] . ' is a ' . $thisproduct['colour'] . $thisproduct['title'] . ', code: ' . $thisproduct['code'];
}

showproductinfo($all_products[1]);

 

:)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.