w3resource

PHP Exercises: Create a new array from two give array of integers, each length 3


101. New Array from Two Arrays

Write a PHP program to create a new array from two give array of integers, each length 3.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes two arrays as parameters
function test($nums1, $nums2)
 { 
    // Return a new array combining the elements of $nums1 and $nums2
    return [$nums1[0], $nums1[1], $nums1[2], $nums2[0], $nums2[1], $nums2[2]];
 }   

// Call the 'test' function with arrays [10, 20, 30] and [40, 50, 60] and store the result in $result
$result = test([10, 20, 30], [40, 50, 60]);

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

Sample Output:

New array: 10,20,30,40,50,60

Flowchart:

Flowchart: Create a new array from two give array of integers, each length 3.

For more Practice: Solve these Related Problems:

  • Write a PHP script to merge two arrays of equal length and output a single concatenated array.
  • Write a PHP function to combine two arrays into one, ensuring no duplicate values appear in the new array.
  • Write a PHP program to join two integer arrays by appending the second to the first and then sorting the result.
  • Write a PHP script to accept two arrays as input and return a new array formed by the sequential combination of both.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to create an array taking two middle elements from a given array of integers of length even.
Next: Write a PHP program to create a new array swapping the first and last elements of a given array of integers and length will be least 1.

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.