views:

2056

answers:

4

Hi, Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?

Below is kind of an explanation of what I won't to do but it isn't the correct syntax.

$number = 0;
echo myArray[$number];
+4  A: 

I'm not sure what you mean. What you have isn't working because you're missing a $ in myArray:

$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi

Unlike other languages, all PHP variable types are preceded by a dollar sign.

Paolo Bergantino
Oh how foolish of me, thank-you.
Ryan
+1  A: 

You are nearly there:

$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number];   // outputs 'a'
Alister Bulman
A: 
$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);

for ($number = 0; $number < $arrSize; $number++) {
echo "$myArray[$number] ";
}

// Output: one two three four
John T
+1  A: 

Hi

Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.

$arrayStates = array('NY' => 'New York', 'CA' => 'California');

To display the values, you can use:

echo $arrayStates['NY']; //prints New York

or, you can also use its numeric index

echo $arrayStates[1]; //prints California

To iterate all values of an array, use foreach or for.

foreach($arrayStates as $state) {
        echo $state;
}

Remember, if foreach is used on non-array, it will produce warning. So you may want to do:

if(is_array($arrayStates)) {
    foreach($arrayStates as $state) {
            echo $state;
    }
}

Hope that helps!

uuɐɯǝʃǝs
No, you can not get the second value from an array with a numeric number. You have to use the key, though type conversion applies so '1' is equal to 1 as a key.
OIS