3

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];
2
  • 2
    Don't edit the question to fix the problem, it won't make sense if anyone ever references it in the future. Commented Apr 9, 2009 at 23:18
  • This is another piece of code that if they tried to actually run it, would throw an error, which might at least have put them onto the right track to fix it. Commented Apr 9, 2009 at 23:30

5 Answers 5

12

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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!

1 Comment

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.
2

You are nearly there:

$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number];   // outputs 'a'

Comments

1
$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);

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

// Output: one two three four

Comments

0
$myArray = array('hi','hiya','hello','gday');

for($count=0;$count<count($myArray);$count++)
{
  $SingleValue = $myArray[$count];
  $AllTogether = $AllTogether.",".$SingleValue;
}

1 Comment

It would probably be helpful to add some notes explaining your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.