:::: MENU ::::
Posts tagged with: PHP

Array Splitting using PHP’s and Java’s in-built Array Funtion

Today, I am going to talk about something simple and useful in programming. For people who are professional programmers this might seem relatively easy but for someone who is trying to learn PHP or Java having a knowlege of how arrays work might be really useful. Especially when you have a large set of data and you need to display it in multiple columns.

So let’s talk about how to use PHP’s and Java’s inbuilt array funtion to slice a large array into smaller parts. For this tutorial, I am assuming you have some knowledge of how PHP and Java works. If not, there are hundreds of websites and books available to get basic understanding.

Scenario: I was given a task to list all the 52 US states in a page so that only the ones that are flagged as active in a table inside database is shown on the page. I had to show this in 3 columns.

#State NameActive Flag
1Alabama1
2Alaska1
3Arizona0
4Arkansas1
51

Result: The result should look something like this.

Alabama
Alaska
Arkansas
California
Kentucky
Louisiana
Maine
Maryland
North Dakota
Ohio
Oklahoma
Oregon

Now, the question might seem relatively easy. And we don’t necessarily need PHP or JAVA to solve this. We could also use something on client side like JavaScript. But, I’ll show how it’s done on the server side.

Query Database for Results:

We can get the list of active states from the database as follows:

SELECT * FROM states where active_flag = 1 order by state_id asc;

For PHP you get the data as follows:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM states WHERE active_flag = 1 ORDER BY state_id ASC;";
$result = $conn->query($sql);
$states = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $states[] = $row;
    }
} else {
    echo "No Results Found";
}

$conn->close();
?>

The above code connects to the database and quries the result and puts it inside the $states[] array.

In Java, you can do the same utilizing Java’s inbuilt database connection library:

Connection conn = null;
CallableStatement stmt = null;
ResultSet result = null;
ArrayList<String> states = new ArrayList<String>();
		
try {
        conn = getConnection();
	stmt = conn.prepareCall("SELECT * FROM states WHERE active_flag = 1 ORDER BY state_id ASC;");

	result = stmt.executeQuery();

	while (result.next()) {

		String state_name = result.getString("state_name");
		states.add(state_name);
	}

} catch (SQLException e) {
	LOG.log(Level.SEVERE, e.getMessage(), e);

} finally {
	result.close();
	stmt.close();
	conn.close();
}

The above code puts the result inside states array. Here, getConnection() actually connects to the database. You can google and read about how to connect to database in Java to understand it much better. But, the idea is simple. We utilize Java’s SQL library to automatically connect to the database. You just define all the required connection settings in a properties file (below is just an example).

protected static Connection getConnection() throws SQLException {
     return DriverManager.getConnection("**** Database Name ****");
}

Now that we have our results in an array. Let’s see how we can split the array into three sub arrays.

Array Count or Length

Before we do the actual splitting, we need to know the count of the total states in the array so that we can split the array evenly across the three arrays.

To do this, in PHP we use the inbuilt function count($array).

$states_count=count($states);

In Java we simply we utilize array.length property of an array.

int states_count = states.length;

Divisible by 3

Now that we know the array length, we need to know how to evenly distribute the states into three sets of list. The logic here is to make the length (or count) of the list divisible by 3 so that we can evenly distribute the states among three sets.

The concept of modulus is very helpful here. The modulo operation (or simply modulus) finds the remainder after division of one number by another. To check if a number is divisible by 3 or not we do the following:

  • First, we check to see if the number is even or odd.
  • If even, we add +1 and do the modulo operand on the length. This is done as number % divisor. If this outputs a number, besides 0, then we know the number is not divisible by divisor. Here we know length or count is even as $states_count % 2 gives us 0. If so, we loop and keep on adding 1 ($states_count++;) until we get a number that is divisible by 3 (loop until $states_count % 3 is not 0).
  • If odd, we test and see if this odd number is divisible by 3 ($states_count % 3 == 0). If the number is not divisible by 3 we keep adding 1 until we get a number that is divisible by 3.

In PHP

if($states_count % 2 == 0){
   do {
      $states_count++;
   }while($states_count % 3 != 0);
}else{
   if($states_count % 3 == 0){
      //do nothing
   }else{
      do {
	 $states_count++;
      }while($states_count % 3 != 0);
   }
}

In Java

if(states_count % 2 == 0){
   do {
      states_count++;
   }while(states_count % 3 != 0);
}else{
   if(states_count % 3 == 0){
      //do nothing
   }else{
      do {
	 states_count++;
      }while(states_count % 3 != 0);
   }
}

Split Array in 3

Now that we have an array length that is divisible by 3, we can do the following to split the array.

In PHP we will use array_slice() method to slice into three parts. The syntax for array_slice() is

array_slice(array, starting index, length);

$states_first = array_slice($states, 0, $states_count/3);
$states_second = array_slice($states, $states_count/3, $states_count/3);
$states_third = array_slice($states, ($states_count/3)*2, $states_count/3);

In Java we will use Arrays.copyOfRange method to make a copy of or split an array. The syntax for copyOfRange() is

int[] newArray = Arrays.copyOfRange(array, starting index, ending index);

ArrayList<String> states_first = new ArrayList<String>();
ArrayList<String> states_second = new ArrayList<String>();
ArrayList<String> states_third = new ArrayList<String>();

states_first = Arrays.copyOfRange(states, 0, states_count/3);
states_second = Arrays.copyOfRange(states, states_count/3, (states_count/3)*2);
states_third = Arrays.copyOfRange(states, (states_count/3)*2, states_count);

And there you go! That’s how you split an array. You can split into any number using the same concept. Let me know what you think or if you have an even better way.