Randomize Multidimensional Associative Array in PHP


In this tutorial, I will explain how to use PHP array_rand() function with the multidimensional associative array to get some random character set. As usual, I will explain the function with a real life example. Our aim is to accept 3 numbers from the user between 1 to 9 and then output 3 random characters correspond to the individual number. Each number store 3 alphabets eg 1 store A, B, C similarly 2 store D, E, F and 3 store G, H, I etc. If user input is 132 then our required output is any single random letter from ABC and GHI and DEF (For example BID). A tricky problem right? but actually, PHP has a huge number of built-in functions (about 9957) which make solving a tricky problem like above a simple task. 

SO LET'S START CODING

The complete PHP code for achieving above task is given below

<?php

if(isset($_POST['submit']))
{
	$input = $_POST['numbers'];

	$data = [
		1 => ['A','B','C'],
		2 => ['D','E','F'],
		3 => ['G','H','I'],
		4 => ['J','K','L'],
		5 => ['M','N','O'],
		6 => ['P','Q','R'],
		7 => ['S','T','U'],
		8 => ['V','W','X'],
		9 => ['Y','Z']
	];

	$input_array = str_split($input,1); 

	// print_r ($input_array);  
	 
	foreach ($input_array as $number)
	{
		
		foreach( $data[$number] as $alphabet)
		{
			$alphabet_array[] = $alphabet; 
		}

		//print_r($alphabet_array);
		$random_numbers = array_rand($alphabet_array,1); 
		
		$output_array[] = $alphabet_array[$random_numbers];

		unset($alphabet_array);	
		
	}
}
if(!empty($output_array))
{
        foreach($output_array as $value)
        {
		echo $value." ";
	}
}

 

Now let me explain the program one by one.

First, we need to store the data as an associative multidimensional array. An Associative array is a type of array which stores values in key value pair. This helps us to extract values just by using the keys.

Second, we need to store post input numbers into individual array elements. In PHP the str_split() function splits a string into an array. Note I used print_r function frequently in my programs for quick debugging.

Now we use a foreach loop to iterate over our numbers and we use another foreach loop to iterate over individual alphabets corresponds to that numbers. We store alphabets of the individual number in an alphabet_array. 

Now we need to pick a random alphabet from this alphabet array. We use array_rand() function for this. But the array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.

Syntax
array_rand(array,number)
Now using the random key value we will extract the alphabet corresponds to alphabet_array and store it on an output_array. The alphabet_array is unset at end of each foreach loop to avoid duplication. 
 
 
Now let's make our program a little colourful by giving some HTML and CSS to it. I used Bootstrap for achieving it. So the complete code for the index.php page is given below.
<?php
if(isset($_POST['submit']))
{
	$input = $_POST['numbers'];

	$data = [
		1 => ['A','B','C'],
		2 => ['D','E','F'],
		3 => ['G','H','I'],
		4 => ['J','K','L'],
		5 => ['M','N','O'],
		6 => ['P','Q','R'],
		7 => ['S','T','U'],
		8 => ['V','W','X'],
		9 => ['Y','Z']
	];

	$input_array = str_split($input,1); // The str_split() function splits a string into an array.

	// print_r ($input_array);  
	 
	foreach ($input_array as $number)
	{
		
		foreach( $data[$number] as $alphabet)
		{
			$alphabet_array[] = $alphabet; // To store alphabets one by one
		}

		//print_r($alphabet_array);
		$random_numbers = array_rand($alphabet_array,1); // array_rand  function gives a random index value of $output array
		
		$output_array[] = $alphabet_array[$random_numbers];

		unset($alphabet_array);	
		
	}
}
?>
<html>
  <head>
    <title>PHP Array Random Function Demo</title>
	
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	
  </head>
  <body>
    <div class="container">
		<div class="row">
			<div class="col-md-6 col-md-offset-3">
				<h2 class="text-center" style="color:#337ab7;"><u>PHP Array Random Function Demo</u></h2>
				<form  action="" method="POST" >
					<div class="form-group">
						<label for="inputName" class="control-label">Numbers</label>
						<input type="text" name="numbers" pattern="[1-9]{1,3}" value="<?php echo isset($_POST['numbers']) ? $_POST['numbers'] : '' ?>" class="form-control"  placeholder="Enter Any 3 Numbers From 1 to 9" required/>
					</div>
					<button class="btn btn-block btn-primary"  type="submit" name="submit">Submit</button>
				</form>
				<h2 class="text-center" style="color:#337ab7;">
					<?php
					    if(!empty($output_array))
						{
							foreach($output_array as $value)
							{
								echo $value." ";
							}
						}
					?>
				</h2>
				<table class="table table-bordered table-striped text-center">
					<thead>
						<tr>
							<th  class="text-center">Number</th>
							<th  class="text-center">Values</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td>1</td>
							<td>A B C</td>
						</tr>
						<tr>
							<td>2</td>
							<td>D E F</td>
						</tr>
						<tr>
							<td>3</td>
							<td>G H I</td>
						</tr>
						<tr>
							<td>4</td>
							<td>J K L</td>
						</tr>
						<tr>
							<td>5</td>
							<td>M N O</td>
						</tr>
						<tr>
							<td>6</td>
							<td>P Q R</td>
						</tr>
						<tr>
							<td>7</td>
							<td>S T Q</td>
						</tr>
						<tr>
							<td>8</td>
							<td>V W X</td>
						</tr>
						<tr>
							<td>9</td>
							<td>Y Z</td>
						</tr>
					</tbody>
				  </table>
				
			</div>
		</div>
		
	<br>
	</div>
  </body>
</html>

 

Note I used HTML validation only in this case which is only necessary in the case of demo programs like this. The HTML input validation offers regular expression checking for advanced pattern matching. The pattern attribute is used for achieving it but remember that it will work only in text inputs. 

The output image of above program is given below.

PHP array_rand function demo program - shareurcodes

The Demo

You can demo above program by visiting following link.

https://shareurcodes.com/demo/random.php

I made this tutorial to prove that PHP is one of the easiest programming languages out there and the huge number of built in functions make programming in PHP much easier.  If anybody has any suggestions or doubts or need any help comment below and I try will response to every one of you as early as possible.


Similar Posts

Web development
16th May 2017 04:34:58 AM
PHP Bootstrap HTML & CSS
5371

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.