Use of some array functions in better way in PHP

By: Array99      Posted On: 04 Nov, 2017      Category: PHP

There are a number of functions in PHP but even after using PHP for years, we stumble upon using built-in functions and their features. Some of these can be quite useful to use better ways. Here, there are some functions and their better way of uses.

Use of substr()

 Suppose you have to find a fixed number of characters from the end of the string. Simply use as below:

<?php
    $string = "Hello world";
    $subString = substr($string, -4);
    echo $subString; //Output orld
?>

 

Use of array_map()

array_map() is very useful function. Many times, we need to trim and remove HTML tags from data that are posted from a form. We can do this by using this function as below:

<?php
if(isset($_POST['submit']) && $_POST['submit'] != ""){
    $postData = array_map('trim', $_POST);
    $postData = array_map('strip_tags', $postData);
     print_r($postData);
}
?>

 

Use of array_column() and array_search()

array_column() function is used to filter data on the basis of key and returns a single array. Let’s take an example of players and their games.

<?php
$players = array(
		     array("id" => 1, "name" => "Sachin", "game" => "Cricket"),
		     array("id" => 2, "name" => "Adam", "game" => "Football"),
		     array("id" => 3, "name" => "Gayle", "game" => "Cricket"),
		     array("id" => 4, "name" => "Rohit", "game" => "Cricket"),
		     array("id" => 5, "name" => "Mark", "game" => "Football"),
		);
$players1 = array_column($players, "name", "id");
print_r($players1);

//Output Array ( [1] => Sachin [2] => Adam [3] => Gayle [4] => Rohit [5] => Mark )
?>

array_column() has first parameter $players which is a set of data, name key is used to filter all player’s name and id is used to get corresponding key value. So the result array is as below:
Array ( [1] => Sachin [2] => Adam [3] => Gayle [4] => Rohit [5] => Mark )

Now, suppose any player’s name have to search in $players data set. You can write code as below:

<?php
$playerName = "Sachin";
if(array_search($playerName, array_column($players, "name", "id")) !== false)
{
	echo "Player Found";
}
else
{
	echo "Player Not Found";
}
?>

Thus, by using both functions you can filter and search a record.

 

Use of array_fill()

This is also a useful function. Let’s take an example as below:

<?php
$players = array(
		array('1', 'Sachin', 'India'),
		array('2', 'Rohit'),
		array('3', 'Tom', 'USA', '12345', 'NY'),
		array('4', 'Thomson',),
		array('5', 'Adam', 'AUS', '9875'),
		array('6', 'John', 'UK'),
		);

?>

$players is a dataset of player’s addresses that are not complete. This type of data is difficult to manage in displaying on a page or exporting in CSV and excel because of number of indexes is not maintained. Here we can use array_fill() function to make same number of indexes as below:

$max = 5;//Suppose max index value 5
foreach($players as $k => $v)
{
	$totalIndex = count($v);
	if($totalIndex <= 5)
	{
		$blanks = array_fill(($totalIndex - 1), (5 - $totalIndex), '');
		$players[$k] = array_merge($v, $blanks);
	}
}

Thus whole program is as below:

<?php
$players = array(
		array('1', 'Sachin', 'India'),
		array('2', 'Rohit'),
		array('3', 'Tom', 'USA', '12345', 'NY'),
		array('4', 'Thomson',),
		array('5', 'Adam', 'AUS', '9875'),
		array('6', 'John', 'UK'),
		);
$max = 5;//Suppose max index value 5
foreach($players as $k => $v)
{
	$totalIndex = count($v);
	if($totalIndex <= 5)
	{
		$blanks = array_fill(($totalIndex - 1), (5 - $totalIndex), '');
		$players[$k] = array_merge($v, $blanks);
	}
}
echo "<pre>";
print_r($players);
echo "</pre>";
?>
/*Output:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Sachin
            [2] => India
            [3] => 
            [4] => 
        )

    [1] => Array
        (
            [0] => 2
            [1] => Rohit
            [2] => 
            [3] => 
            [4] => 
        )

    [2] => Array
        (
            [0] => 3
            [1] => Tom
            [2] => USA
            [3] => 12345
            [4] => NY
        )

    [3] => Array
        (
            [0] => 4
            [1] => Thomson
            [2] => 
            [3] => 
            [4] => 
        )

    [4] => Array
        (
            [0] => 5
            [1] => Adam
            [2] => AUS
            [3] => 9875
            [4] => 
        )

    [5] => Array
        (
            [0] => 6
            [1] => John
            [2] => UK
            [3] => 
            [4] => 
        )

)
*/

 

Use of array_combine()

This function is used to create an array by using one array for keys and another for its values. Sometimes, we get two type of dataset in which one have to make key and other make value. In below, there are two arrays one has player’s ids and second has player’s names.

<?php
$playerIds = array('1', '2', '3', '4', '5');
$playerNames = array('Sachin', 'Rohit', 'Tom', 'Adam', 'John');
?>

  Now, we combine both arrays such that values of $playerIds will be keys and values $playerNames will be values.

<?php
$playerIds = array('1', '2', '3', '4', '5');
$playerNames = array('Sachin', 'Rohit', 'Tom', 'Adam', 'John');
$players = array_combine($playerIds, $playerNames);

echo "<pre>";
print_r($players);
echo "</pre>";
/*Output:
Array
(
    [1] => Sachin
    [2] => Rohit
    [3] => Tom
    [4] => Adam
    [5] => John
)
*/
?>

 

You may like: