New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes Print Numbers from 1 to N without using loop in PHP

Print Numbers from 1 to N without using loop in PHP

0

Welcome back to shortlearner.com, today we will learn how to print 1 to N number without using any type of loop.
In this tutorial we print 1 to N number with the help of some php functions like range() and array_walk.
1 to N without using loop in PHP
The range() function is used to create an array of elements of any kind such as integer, alphabets within a given range(from low to high) i.e, list’s first element is considered as low and last one is considered as high.
syntax of range function is like

array range(low, high, step)

It returns an array of elements from low to high.
for example

<?php
$numbers = range(0, 100);
print_r($numbers);
?>

array_walk()
The array_walk() function apply a user defined function to every element of an array. The user-defined function takes array’s values and keys as parameters.

<?php
$array = range(1, 100);
array_walk($array, function ($value) {
echo "$value";
});

?>

and the another way to print 1 to N number is

<?php
print_number(1);
function print_number($number) {
if($number > 100) {
return;
} else {
echo "$number";
echo "<br/>";
print_number(++$number);
}
}
?>