Programming 3. Write a function removeAllValuesMatching($arr, $value) that takes
ID: 641474 • Letter: P
Question
Programming
3. Write a function removeAllValuesMatching($arr, $value) that takes an associative array and a value as a parameter and returns a new associative array in which any array value matching $value is removed. In other words,
$arr = array(
'a' => "one",
'b' => "two",
'c' => "three",
'd' => "two",
'e' => "four",
'f' => "five",
'g' => "three",
'h' => "two"
);
print_r(removeAllValuesMatching($arr, "two"));
would print:
Array
(
[a] => one
[c] => three
[e] => four
[f] => five
[g] => three
)
2
4. Write a function removeDuplicates($arr) that takes an associative array as a parameter and returns the same associative array except with all duplicate values removed.
You may not use the function array_unique for this problem. For example:
$arr = array(
'a' => "one",
'b' => "two",
'c' => "three",
'd' => "two",
'e' => "four",
'f' => "five",
'g' => "three",
'h' => "two"
);
print_r(removeDuplicates($arr));
Would print:
Array
(
[a] => one
[e] => four
[f] => five
)
5. Write a function findSpellings($word, $allWords) that takes a string and an array of dictionary words as parameters. The function should return an array of possible spellings for a misspelled $word. One way to approach this is to use the soundex() function to find words in $allWords that match the soundex for $word.
Explanation / Answer
3)
Program Code:
<?php
function removeAllValuesMatching($arr, $del_value)
{
foreach ($arr as $key => $value)
{
if ($value == $del_value)
{
unset($arr[$key]);
}
}
return $arr;
}
$arr = array('a' => "one",'b' => "two",'c' => "three",'d' => "two",'e' => "four",'f' => "five",'g' => "three",'h' => "two");
print_r(removeAllValuesMatching($arr, "two"));
?>
Sample output:
sh-4.2# php main.php
Array
(
[a] => one
[c] => three
[e] => four
[f] => five
[g] => three
)
4)
Program Code:
<?php
function removeDuplicates($arr)
{
$result = array_unique($arr);
return $result;
}
$arr = array('a' => "one",'b' => "two",'c' => "three",'d' => "two",'e' => "four",'f' => "five",'g' => "three",'h' => "two");
print_r(removeDuplicates($arr));
?>
Sample output:
sh-4.2# php main.php
Array
(
[a] => one
[b] => two
[c] => three
[e] => four
[f] => five
)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.