Home>Article>Backend Development> PHP Algorithm Exercise 4: Multiply the corresponding elements of two given lists
This article continues to introduce the algorithm exercise series to you. In the previous article "PHP Algorithm Exercise 3: Exchange the first and last characters in the string", I introduced to you how to exchange the characters in the string. The first and last characters, interested friends can learn about it~
Now I will ask you a question: "How to write a PHP program to multiply the corresponding elements of two given lists" ?
What does it mean?
As shown in the picture below, just multiply the data corresponding to the two rows!
Okay, let’s go straight to the code:
The PHP code is as follows:
$value){ $output[$key] = $a[$key]*$b[$key]; } return implode(' ',$output); } echo multiply_two_lists(("10 12 3"), ("1 3 3"))."
";
The output result is
In the above example, we gave two columns of data, namely 10, 12, 3 and 1, 3, 3.
Then multiply the corresponding elements of the two given lists, that is, find 10*1, 12*3, 3*3.
Obviously, the results of multiplication are 10, 36, and 9 respectively.
Here are 2 functions that you need to know about:
trim()
Function: remove blank characters or other predefined characters on both sides of the string .
→Attached related functions: ltrim() removes blank characters or other predefined characters on the left side of the string. rtrim() removes whitespace characters or other predefined characters from the right side of a string.
explode()
Function: Break up the string into an array.
The syntax is "explode(separator,string,limit)
", and the return value is an array of returned strings.
→Note: The "separator" parameter cannot be an empty string. This function is binary safe.
I won’t introduce much about the foreach loop here. You can read the article "Usage of foreach in PHP".
Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!
The above is the detailed content of PHP Algorithm Exercise 4: Multiply the corresponding elements of two given lists. For more information, please follow other related articles on the PHP Chinese website!