Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle value inside Loop and concatenate with array

Tags:

arrays

php

I do have a requirement where in Inside an array i need to shuffle the values.

Below is the code Snippet

$vehicle = array('hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv');
$RequiredVehicle = 3;

$vehicleList = array();


for($i=0;$i<count($vehicle);$i++)
{
  $vehicleList[] =$vehicle[$i].$RequiredVehicle;
}

echo "<pre>";
print_r($vehicleList);

The Output what i am getting is

Array
(
    [0] => hcv3
    [1] => hcv3
    [2] => hcv3
    [3] => hcv3
    [4] => hcv3
    [5] => hcv3
    [6] => hcv3
    [7] => hcv3
    [8] => hcv3
    [9] => hcv3
)

The Actual output what i need is

Array
(
    [0] => hcv1
    [1] => hcv2
    [2] => hcv3
    [3] => hcv1
    [4] => hcv2
    [5] => hcv3
    [6] => hcv1
    [7] => hcv2
    [8] => hcv3
    [9] => hcv1
)

There are 10 vehicles and 3 Required vehicles so The output what i need is total vehicles should be shuffled between 3 Required vehicles

if its $vehicle = 10 and $RequiredVehicle = 3 then Array value should be 1,2,3,1,2,3,1,2,3,1

if its $vehicle = 10 and $RequiredVehicle = 2 then Array value should be 1,2,1,2,1,2,1,2,1,2

like image 371
Shreyas Achar Avatar asked Jan 24 '26 23:01

Shreyas Achar


1 Answers

That is because you are just appending the $RequiredVehicle

You can use modulo % the $i and add 1. Like ( ( $i % $RequiredVehicle ) + 1 )

$vehicle = array('hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv');
$RequiredVehicle = 3;

$vehicleList = array();
for($i=0;$i<count($vehicle);$i++)
{
   $vehicleList[] =$vehicle[$i] . ( ( $i % $RequiredVehicle ) + 1 );
}

echo "<pre>";
print_r($vehicleList);

This will result to:

Array
(
    [0] => hcv1
    [1] => hcv2
    [2] => hcv3
    [3] => hcv1
    [4] => hcv2
    [5] => hcv3
    [6] => hcv1
    [7] => hcv2
    [8] => hcv3
    [9] => hcv1
)
like image 194
Eddie Avatar answered Jan 27 '26 13:01

Eddie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!