String Parsing and Arithmetic Operations in PHP

Introduction

Welcome! In this unit, we will dive into an engaging task that tests your PHP programming skills. We will explore string manipulation by parsing strings and performing arithmetic operations on extracted data. Let's get started!

Task Statement and Description

Our task for today involves creating a PHP function called parseAndMultiplyNumbers(). This function is designed to accept a string as input. However, it's not just any string — this input will include a playful mix of numbers and words.

The purpose of the function is to analyze the input string, extract all the numbers, convert these numbers (currently in string form) into integer data types, and then multiply all these numbers together. The final output will be the product of all those numbers!

Here's an illustration: Given the input string "I have 2 apples and 5 oranges", our function should return the product of 2 and 5, which is 10.

Step-by-Step Solution Building: Step 1

The primary task is to parse the string and identify the numbers. We'll start by creating an empty string, $num, to accumulate digits, and an empty array to collect all the numbers we find:

PHP
$inputString = "I have 2 apples and 5 oranges";
$num = "";
$numbers = [];

Step-by-Step Solution Building: Step 2

Next, we need to iterate through the input string character by character. When we encounter a digit, we append it to our $num string. If a character isn’t a digit and $num isn’t empty, it means we've reached the end of a number.

At this point, we convert $num to an integer, add it to the numbers array, and reset $num to an empty string. If the character isn’t a digit and $num is empty, we simply skip and continue.

PHP
for ($i = 0; $i < strlen($inputString); $i++) {
    $ch = $inputString[$i];
    if (ctype_digit($ch)) {
        $num .= $ch;
    } elseif (!empty($num)) {
        $numbers[] = intval($num);
        $num = "";
    }
}
// After the loop, check if 'num' is not empty
// because it indicates that the last part of the string contains a number.
if (!empty($num)) {
    $numbers[] = intval($num);
}
foreach ($numbers as $number) {
    echo $number . " ";
}

After running this code, the output should be 2 5.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal