Syntax for array_slice() and Usage.
array_slice(array, start, length, preserve)
Parameter Description
array Specifies an input array.
start If offset is non-negative, the sequence will start at that offset in the array.If offset is negative, the sequence will start
that far from the end of the array.
length If length is given and is positive, then the sequence will have up to that many elements in it.
If the array is shorter than the length, then only the available array elements will be present.
If length is given and is negative then the sequence will stop that many elements from the end of the array.
If it is omitted, then the sequence will have everything from offset up until the end of the array.
preserve Specifies if the function should preserve or reset the keys. Possible values:
true - Preserve keys
false - Default. Reset keys
Split single array into two arrays.
Let's learn
1.Create php file as array.php.
2.Create single array in that array.php
$input = array("bike1", "bike2", "bike3", "bike4", "bike5");
3.Using this function array_slice()
you can slice an array using array_slice() to cut an array in any number of arrays.
array_slice()
4.Complete code for Array Split
<html>
<head>
<title>Split single array into two arrays.</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container ">
<div class="text-center">
<h1>Split Single Array into Two Arrays.</h1>
</div>
<br>
<div class="well">
<?php
$input = array("bike1", "bike2", "bike3", "bike4", "bike5");
$len = count($input);
$firsthalf = array_slice($input, 0, $len / 2);
$secondhalf = array_slice($input, $len / 2);
echo"<h3>First Array</h3>";
echo "<br>";
print_r($firsthalf);
echo "<br>";
echo "<br>";
foreach($firsthalf as $fa){
echo $fa;
echo "<br>";
}
echo "<br>";
echo"<h3>Second Array</h3>";
echo "<br>";
print_r($secondhalf);
echo "<br>";
foreach($secondhalf as $sa){
echo $sa;
echo "<br>";
}
?>
</div>
<div>
</div>
</div>
</body>
</html>