w3resource

PHP Exercises: Create a new array taking the first and last elements of a given array of integers and length 1 or more

PHP Basic Algorithm: Exercise-94 with Solution

Write a PHP program to create a new array taking the first and last elements of a given array of integers and length 1 or more.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($nums)
 { 
    // Return a new array containing the first and last elements of the input array
    return [$nums[0], $nums[sizeof($nums) - 1]];
 }   

// Create an array $a with some numeric values
$a = [10, 20, -30, -40, 30];

// Print the original array as a string using 'implode' and 'echo'
echo "Original array: " . implode(',', $a) . "\n";

// Call the 'test' function with the array $a and store the result in $result
$result = test($a);

// Print the new array containing the first and last elements using 'implode' and 'echo'
echo "New array: " . implode(',', $result);
?>

Sample Output:

Original array: 10,20,-30,-40,30
New array: 10,30

Flowchart:

Flowchart: Create a new array taking  the first and last elements of a given array of integers and length 1 or more.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find out the maximum element between the first or last element in a given array of integers ( length 4), replace all elements with maximum element.
Next: Write a PHP program to check if a given array of integers and length 2, contains 15 or 20.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.