Showing posts with label PHP array_map. Show all posts
Showing posts with label PHP array_map. Show all posts

Friday, 2 August 2019

How to convert all $_POST or $_GET values to Integers

By using the built-in PHP functions  array_map and intval.
  • array_map = Applies the callback to the elements of the given arrays, this applies the function for each value of an array (PHP 4 >= 4.0.6, PHP 5)
  • intval = Get the integer value of a variable (PHP 4, PHP 5)
Examples:
{codecitation style=”brush: PHP;”}
$post_int = array_map(‘intval’, $_POST); //Converting every post value to integer
$get_int = array_map(‘intval’, $_GET); //Converting every get value to integer
{/codecitation}

Thursday, 30 August 2018

PHP: Sort set based on another table


 I have visited similar question here but not getting what i want in php. Suppose i have 2 arrays. All checking should be case insensitive. say Field0 is same as field0 or fiEld1 is same as Field1.


array1 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
);

array2 is array(
"0"=>"field3",
"1"=>"field2",
"2"=>"field0",
"3"=>"field1",
"4"=>"field6",
"5"=>"field5",
);

Now I want array2 to be sorted based on array1 like the following:
array2 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
"4"=>"field6",
"5"=>"field5",
);

look here array1 has 4 elements so array2 should be sorted based exactly 4 elements of array1 and rest 2 element (index 4,5 of array2) should as it is in array2 before.

Try array_intersect combined with array_diff:
<?php
$array1 = array(
    "0"=>"field0",
    "1"=>"field1",
    "2"=>"field2",
    "3"=>"field3",
);

$array2 = array(
    "0"=>"field3",
    "1"=>"field2",
    "2"=>"field0",
    "3"=>"field1",
    "4"=>"field6",
    "5"=>"field5",
);

$array3 = array_merge(
    array_intersect($array1, $array2),
    array_diff($array2, $array1)
);

var_dump($array3);

Update
For a case insensitive approach, use array_map to guarantee all entries in both arrays are lower-cased:
$array3 = array_map('strtolower', $array1);
$array4 = array_map('strtolower', $array2);

$array5 = array_merge(
    array_intersect($array3, $array4),
    array_diff($array4, $array3)
);

var_dump($array5);

PHP sorting table based on three internal table key values


I am looking to do some complex array sorting, but I have no idea where to start. The inner array has three relevant keys for sorting: first the year (numerical ASC), then the month (numerical ASC) and finally the name (alphabetical DESC).


<?php
// the current array:
$array = (
  array('year'=>2012, 'month'=>3, 'name'=>'John', 'score'=>12),
  array('year'=>2013, 'month'=>8, 'name'=>'Paul', 'score'=>3),
  array('year'=>2013, 'month'=>5, 'name'=>'Dennis', 'score'=>7),
  array('year'=>2012, 'month'=>3, 'name'=>'Paul', 'score'=>5),
  array('year'=>2012, 'month'=>12, 'name'=>'Paul', 'score'=>9),
  array('year'=>2012, 'month'=>9, 'name'=>'Mitt', 'score'=>3)
);

// I want to do some sorting with this as output:
$array = (
  array('year'=>2012, 'month'=>3, 'name'=>'John', 'score'=>12),
  array('year'=>2012, 'month'=>3, 'name'=>'Paul', 'score'=>5),
  array('year'=>2012, 'month'=>9, 'name'=>'Mitt', 'score'=>3),
  array('year'=>2012, 'month'=>12, 'name'=>'Paul', 'score'=>9),
  array('year'=>2013, 'month'=>5, 'name'=>'Dennis', 'score'=>7),
  array('year'=>2013, 'month'=>8, 'name'=>'Paul', 'score'=>3)
);
?>

If anyone can point me in the right direction that is really appreciated ;-).

This should work...
<?php
    // Obtain a list of columns
    // PHP 5 >= 5.5.0
    $years  = array_column($array, 'year');
    $months = array_column($array, 'month');
    $names  = array_map('strtolower', array_column($array, 'name')); // because it's a string sort.

    // Sort the data with volume descending, edition ascending
    // Add $data as the last parameter, to sort by the common key
    array_multisort($years, SORT_ASC, $months, SORT_ASC, $names, SORT_DESC, $array);
?>

EDIT : for PHP < 5.5
<?php
    // Obtain a list of columns
    // PHP < 5.5.0
    foreach ($array as $key => $row) {
        $years[$key]  = $row['year'];
        $months[$key] = $row['month'];
        $names[$key]  = strtolower($row['name']); // because it's a string sort.
    }
?>

Monday, 23 February 2015

PHP: Extract keywords from a webpage

The title said it all: A great code snippet to easily extract meta keywords from any webpage.
<?php
$meta = get_meta_tags('https://thiscode4u.blogspot.com/');
$keywords = $meta['keywords'];
// Split keywords
$keywords = explode(',', $keywords );
// Trim them
$keywords = array_map( 'trim', $keywords );
// Remove empty values
$keywords = array_filter( $keywords );

print_r( $keywords );
?>

Wednesday, 24 September 2014

array_map in PHP

PHP array_map() function sends every value of an array to a user-made function, and gives back an array with new values, given by the user-defined function. 

Syntax for PHP array_map()

array_map(function,array1,array2,array3...)
function : Required. Name of the user-made function, or null
array1 : Required. Specifies an array
array2 : Optional. Specifies an array
array3 : Optional. Specifies an array
Tip : You can assign one array to the function, or as many as you like.

Example on PHP array_map()

<?php
function myfunc($par1,$par2)
{
if($par1===$par2)
{
return "same";
}
return "different";
}
$daysarr1 = array("Sunday","Monday","Tuesday");
$daysarr2 = array("Wednesday","Friday","Tuesday");
print_r(array_map("myfunc",$daysarr1,$daysarr2));
$daysarr1 = array("Sunday","Monday");
$daysarr2 = array("Tuesday","Wednesday");
echo "<br />"."assigning function name as null";
print_r(array_map(null,$daysarr1,$daysarr2));
?>

Output will be:

Array (
           [0] => different
           [1] => different
           [2] => same
         ) 
assigning function name as null
Array (
          [0] => Array (
                               [0] => Sunday
                               [1] => Tuesday
                             )
          [1] => Array (
                               [0] => Monday
                               [1] => Wednesday
                             )
          )
 
 
Brief Explanation about array_map():
 
array_map():Applies the callback to the elements of the given arrays 
Syntax:array array_map( callable $callback, array $array1[, array $...])
 
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()


Parameters: 

callback

Callback function to run for each element in each array.
array1
An array to run through the callback function.
...
Variable list of array arguments to run through the callback function.

Return Values

Returns an array containing all the elements of array1 after applying the callback function to each one.
 
 Example:
<?phpfunction cube($n)
{
    return(
$n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);$b = array_map("cube", $a);print_r($b);?>

Output:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
 
Example2:
<?php
$func 
= function($value) {
    return 
$value * 2;
};
print_r(array_map($func, range(1, 5)));?>
Output: 

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)