How can associative arrays with matching keys be multiplied in PHP?
When multiplying associative arrays with matching keys in PHP, you can loop through the arrays, multiply the values with the same keys, and store the result in a new array. This can be achieved by using a foreach loop to iterate over one of the arrays and checking if the key exists in the other array before performing the multiplication.
$array1 = ['a' => 2, 'b' => 3, 'c' => 4];
$array2 = ['a' => 5, 'b' => 2, 'c' => 1];
$result = [];
foreach ($array1 as $key => $value) {
if (array_key_exists($key, $array2)) {
$result[$key] = $value * $array2[$key];
}
}
print_r($result);
Related Questions
- What security considerations should be taken into account when transferring data to an external site in PHP?
- What are the potential pitfalls to be aware of when searching for a string in an array in PHP?
- What are the advantages of using hash functions like Whirlpool instead of md5 or sha1 for storing passwords in a database?