<?php /** * Find the second largest item in an array * * the quick way would be arsort($strings); echo $strings[1]; */ $strings = array('aaa', 'aaaaaa', 'a', 'a', 'aa', 'aaaa', 'a', 'aaaaaaaaaa', 'aaa'); function secondLargest(array $elements) { if (count($elements) == 1) { return $elements[0]; } unset($elements[largestElement($elements)]); return $elements[largestElement($elements)]; } function largestElement(array $elements) { $largest = array('key' => 0, 'size' => 0); foreach ($elements as $key => $element) { if (strlen($element) > $largest['size']) { $largest = array('key' => $key, 'size' => strlen($element)); } } return $largest['key']; } #arsort($strings); #echo $strings[1]; echo "\n=========== Exercise 2 ===========\n"; echo secondLargest($strings); echo "\n=========== End Exercise 2 =======\n";
<?php // Enter various combinations of numbers and letters to test program. print 'This uses if statements.' . '<br /><br />'; // Calls made to function secondLargest passing in three values. $result = secondLargest(2, 5, 7); print 'For input of 2,5,7 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargest(5, 7, 2); print 'For input of 5,7,2 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargest(7, 2, 5); print 'For input of 7,2,5 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargest(7, 5, 2); print 'For input of 7,5,2 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargest(2, 2, 7); print 'For input of 2,2,7 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargest(2, 5, 'seven'); print 'For input of 2,5,seven ' . 'the answer is ' . $result . '<br /><br /><br />'; print 'This uses an array.' . '<br /><br />'; // Calls made to function secondLargestArray passing in three values. $result = secondLargestArray(2, 5, 7); print 'For input of 2,5,7 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargestArray(5, 7, 2); print 'For input of 5,7,2 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargestArray(7, 2, 5); print 'For input of 7,2,5 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargestArray(7, 5, 2); print 'For input of 7,5,2 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargestArray(2, 2, 7); print 'For input of 2,2,7 ' . 'the answer is ' . $result . '<br /><br />'; $result = secondLargestArray(2, 5, 'seven'); print 'For input of 2,5,seven ' . 'the answer is ' . $result . '<br /><br />';