user1721230
user1721230

Reputation: 315

substitute some values in a string

So I'm trying to get the below code to substitute only the values in the string, so Maths = 1, English = 1 and Media (short course) = 0.5. So that should output 2.5, however its outputting 14. I guess that means its adding up all the values in the array.

So I want to replace values in a string with certain numeric values then add them up. Any ideas?

$strg2 = 'Maths, English, Media (Short course)';

$gcse = explode(',', $strg2);
$gcse = array(
'Maths' => '1',
'English' => '1',
'EnglishLit' => '1',
'Science' => '1',
'Art' => '1',
'ICT (full course)' => '1',
'ICT (Short course)' => '0.5',
'Media (Full course)' => '1',
'Media (Short course)' => '0.5',
'Geography' => '1',
'History' => '1',
'ChildCare' => '1',
'Religious' => '1',
'Electronics' => '1',
'Higher' => '0.5',
'Foundation' => '0.5');

echo array_sum($gcse);

Upvotes: 0

Views: 46

Answers (2)

Vlad Preda
Vlad Preda

Reputation: 9920

If you want to use only array operations, you can do the following:

$lessons = explode(',', $strg2);
$lessons = array_map('trim', $lessons);
$lessons = array_flip($lessons);
$result = array_intersect_key($gcse, $lessons);

echo array_sum($result);

Otherwise, the solution proposed by @beingalex will be faster in all situations.

PS: Just for fun, a one liner:

echo array_sum(array_intersect_key($gcse, array_flip(array_map('trim', explode(',', $strg2)))));

Upvotes: 0

beingalex
beingalex

Reputation: 2476

I think you're trying to create a "score" based upon the input string, $strg2. You will need to split that string into an array and then iterate it, matching the lessons to the value of the $gcse array.

$strg2 = 'Maths, English, Media (Short course)';

$gcse = array(
'Maths' => '1',
'English' => '1',
'EnglishLit' => '1',
'Science' => '1',
'Art' => '1',
'ICT (full course)' => '1',
'ICT (Short course)' => '0.5',
'Media (Full course)' => '1',
'Media (Short course)' => '0.5',
'Geography' => '1',
'History' => '1',
'ChildCare' => '1',
'Religious' => '1',
'Electronics' => '1',
'Higher' => '0.5',
'Foundation' => '0.5');

$lessons = explode(',', $strg2); // Split the string into an array that can be iterated
$n = 0;

foreach ($lessons as $lesson) {

    $n += $gcse[trim($lesson)]; // n = n + the value of lesson

}

echo $n;

Upvotes: 1

Related Questions