PHP array_map()

📔 : PHP 🔗

array_map() function Array के प्रत्येक value को user defined callback function में send करता है , और एक Array नई values के साथ return करता है।


Basically array_map() function का use Array एक हर एक element को callback function के through visit करने के लिए किया जाता है।

Understanding Callback Function

Callback Functions वो function होते हैं जो किसी दूसरे function में as an arguments pass किये जाते हैं। और जिस function में ये pass किये जाते हैं उन्हें Higher - Order Function कहते हैं।

PHP array_map Syntax

array_map ( callable|null $callback , array $array , array ...$arrays );

  1. callable | null $callback | required : यह user define function है , function normal भी हो सकता है या आप चाहे तो Arrow Function भी pass कर सकते हैं। हालाँकि function की जगह आप null भी pass कर सकते हैं।

  2. array $array | required : बैसे तो आप कई Array एक साथ pass कर सकते हैं , लेकिन first Array required होता है।


PHP array_map Example

File : php-array_map.php

Copy Fullscreen Close Fullscreen
<?php 
    /*Defie function*/
   function myfunction($number)
  {
    return $number * 2;
  } 

  $new_array = array_map('myfunction', [10, 20, 30, 40, 50]);
  echo "<pre>";
  print_r($new_array);
  echo "</pre>"; 
?>
Output
Array
(
    [0] => 20
    [1] => 40
    [2] => 60
    [3] => 80
    [4] => 100
)

Important
अगर हम एक से ज्यादा Array pass करते हैं , और Callback Function की वजाय null pass करते हैं तो , हमें Two Dimensional Array मिलेगा जो कि pass किये गए array values को hold करेगा।

File : php-array_map2.php

Copy Fullscreen Close Fullscreen
<?php 
   $a = [1, 2, 3];
  $b = ['one', 'two', 'three'];
  $c = ['uno', 'dos', 'tres'];

  $d = array_map(null, $a, $b, $c);

  echo "<pre>";
  print_r($d);
  echo "</pre>";
?>
Output
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

)

I Hope अब आपको array_map() function के बारे में clear हो गए होंगे।


PHP TutorialsPHP array_search()PHP in_array()

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook