w3resource

PHP Exercises: Create a new array using the first n strings from a given array of strings

PHP Basic Algorithm: Exercise-134 with Solution

Write a PHP program to create a new array using the first n strings from a given array of strings. (n>=1 and <=length of the array).

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of strings and an integer 'n'
function test($arr_str, $n)
{ 
    // Initialize a new array with a size equal to the number of elements in the input array
    $new_array = [sizeof($arr_str)];

    // Iterate through the array up to the specified 'n' elements
    for ($i = 0; $i < $n; $i++)
    {
        // Copy each element from the input array to the new array
        $new_array[$i] = $arr_str[$i];
    }

    // Return the new array containing the first 'n' elements
    return $new_array;
}

// Call the 'test' function with an array and 'n' value, then use 'implode' to print the result as a string
$result = test(["a", "b", "bb", "c", "ccc"], 3);
echo implode(" ", $result);
?>

Sample Output:

a b bb

Flowchart:

Flowchart: Create a new array using the first n strings from a given array of strings.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to count the number of strings with given length in given array of strings.
Next: Write a PHP program to check a positive integer and return true if it contains a number 2.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-134.php