0

As a php beginner, I meet a problem with calculating the elements of array in php

$effect=array("a"=>array(1,2),"b"=>array(1,2),"c"=>array(1,2));

I just want to make the result as this

$effect['a'][0]=$effect['a'][0]/$effect['a'][1];
$effect['b'][0]=$effect['b'][0]/$effect['b'][1]; 
$effect['c'][0]=$effect['c'][0]/$effect['c'][1];    

Except do this one by one , How to do this calculation with foreach or other loop way

3
  • So your goal is to divide the first element of each sub-array by the second element of the first sub-array? Commented Feb 22, 2013 at 2:29
  • sorry I have made a little mistake ,my goal is to divide the first element of each sub-array by the second element of each sub-array Commented Feb 22, 2013 at 2:32
  • @MichaelBerkowski sorry I have made a little mistake , and i have modified the index:my goal is to divide the first element of each sub-array by the second element of each sub-array Commented Feb 22, 2013 at 2:33

3 Answers 3

1

Your array syntax is a bit off. It should be $effect['a'][0].

The loop is trivial, and foreach was the right idea.
You can use it to iterate over all the letters using:

 foreach ($effect as $letter => $numbers) {

     ...

 }

Then put your assignment/division line in the loop, replacing the fixed 'a' and 'b' etc. with the $letter variable.

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

2 Comments

Is there any difference with what i have written ?"Your array syntax is a bit off. It should be $effect['a'][0]."
Your original post used $effect('a')[0], which is why I noted that.
0

You need something like this?

foreach ($effect as $key => $val)
{

    $results[$key] = $val[0] / $val[1];

}

print_r($results);

Comments

0

Also one counter-intuitive thing in PHP, is that arrays are passed by value by default. You can use & to get a reference to the array

$effects =array("a"=>array(1,2),"b"=>array(1,2),"c"=>array(1,2));
foreach ( $effects as $key => &$effect ) {
   $effect[0] = $effect[0]/$effect[1];
   unset($effect);
}
print_r( $effects );

Comments

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.