1

i have the following array written in PHP. I need a way to print values by name, and if possible, do calculations with specific values (by looping through).

[MAIN] => Array
    (
        [FIRST] => Array
            (
                [0] => 500
                [1] => 1000
                [2] => 1500
            )

        [SECOND] => Array
            (
                [Name] => Nick
                [State] => None

            )

    )

For example, by using the array above i'd like to print only the NAME of the "SECOND" array but without looping through every index (without using an index at all), and add each value of the "FIRST" array by looping throu them.

Thank you!

3
  • 2
    echo $array['MAIN']['SECOND']['Name']; Commented Jan 19, 2014 at 13:58
  • Thank you sir! That did the job! And if i may ask, how can i do math with the values of "FIRST" array? Thanks again!!! Commented Jan 19, 2014 at 14:00
  • ill answer in the answer box Commented Jan 19, 2014 at 14:02

2 Answers 2

4
$result = 0;
foreach ($array['MAIN']['FIRST'] as $val) {
    $result += $val;
}
echo $result;
Sign up to request clarification or add additional context in comments.

Comments

2

The first question is like this:

echo $array['MAIN']['SECOND']['Name'];

You have an array of an array of an array so you have to dereference values as such.

The second one would look something like this:

$var = 0;
for($i = 0; $i < 3; $i++) {
    $var += $array['MAIN']['FIRST'][$i];
}
echo $var;

2 Comments

You type arguments for for cycle, and it's do not work with foreach
oops my bad, started with foreach and changed my mind :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.