Jump to content

[SOLVED] Accessing an array from a function not working for some reason :(


Recommended Posts

$product = array( array("Flash Light", 3, 20), array("Ball", 2, 15), array("Keychain", 7, 10));

function echoName()
{
echo $product[0][1];
}

echoName();
echo $product[0][1];

 

All this does is echo "3" once to me (i should echo it twice, no?). I comment out the last line and i get nothing, i comment out the second last line and i still only get one output! :(

 

Sorry, I started learning html and php today and then i hit this road block :S

Surely calling the function should echo 3?

 

Maybe it's because I've not coded anything in a while (C++, a few years back), and I may just be missing something really obvious, but why the hell is this not working? lol any and all help will be great.

 

Could it be that you cant access an array from a function? :/

 

Thanks in advance :)

The variable $product is not available to the function. This is known as 'scope', and literally means that echoName does not 'see' your variable $product. Functions have their own completely separate set of variables. You can tell the function to 'see' your variable's value two ways. Either send it directly in, or globalize it.

 

Direct in:

<?php
$product = array( array("Flash Light", 3, 20), array("Ball", 2, 15), array("Keychain", 7, 10));

function echoName($product)
{
echo $product[0][1];
}

echoName($product);
echo $product[0][1];

 

Globalize:

<?php
$product = array( array("Flash Light", 3, 20), array("Ball", 2, 15), array("Keychain", 7, 10));

function echoName()
{
    global $product;
    echo $product[0][1];
}

echoName();
echo $product[0][1];

 

PhREEEk

Riiiight! Thanks loads, I'll be on my way forward with PHP now :D

I figured the scope rules would be the same as in C++ where each variable is available to anything below it (metaphorical-heirarchially).

 

Thanks again, I may just stick around, this place seems nice :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.