0
   $a = array ('x' => 2, 'y' => 3);
   $b = array (          'y' => 2, 'z' => 3);

// $c = $a * $b;
// i would like to have

// $c = array ('x' => 0, 'y' => 6, 'z' => 0);
1
  • It sounds like you'd like to do cross products or dot products. Is that the case? Commented Nov 5, 2010 at 18:56

3 Answers 3

2

If you want to multiply any similar keys together, you will need to get a list of the keys. array_keys would appear to be just the function for that.

function foo($a, $b)
{
   foreach(array_keys($a) as $i)
   {
      if(array_key_exists($i, $b){  // exists in a and b
          $result[$i] = $a[$i]*$b[$i];
      }else{  // exists and a but not b
          $result[$i] = 0;
      }
   }
   foreach(array_keys($b) as $i)
   {
      if(not array_key_exists($i, $a){ //exists in b but not i a
          $result[$i] = 0;
      }
   }
   return $result
}

This will (hopefully) work for any set of keys you hand in, not just x, y, and z.

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

Comments

1

You could use array_map and abuse bcmul for this purpose:

array_map( 'bcmul', $a, $b ) == $a * $b

Comments

0

You'll have to use a library or define the cross product yourself:

function cross_product($a, $b)
{
  return array( $a['y'] * $b['z'] - $a['z'] * $b['y'], ...
}

http://en.wikipedia.org/wiki/Cross_product

After further examination of what you're doing, it looks as though you'd like something along the lines of:

function multiply_arr($a, $b)
{
  return array($a['x'] * $b['x'], $a['y'] * $b['y'], $a['z'] * $b['z]);
}

again, you'll have to make your own function, and you ought to do some error checking in case a value is undefined.

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.