DEV Community

Morcos Gad
Morcos Gad

Posted on

Some method in PHP may work for you in your code

Let's start quickly with array_filter. I want to extract some results, let them be odd numbers, so what should I do

function test_odd($var)
{
  return($var & 1);
}

$a1=array(1,3,2,3,4);
print_r(array_filter($a1,test_odd)); //Array ( [0] => 1 [1] => 3 [3] => 3 )
Enter fullscreen mode Exit fullscreen mode

I want to do some arithmetic work on this array

function myfunction($num)
{
  return($num*$num);
}

$a=array(1,2,3,4,5);
print_r(array_map(myfunction,$a)); //Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
Enter fullscreen mode Exit fullscreen mode

I want to get the values ​​for the array only

$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a)); //Array ( [0] => Peter [1] => 41 [2] => USA )
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.

Top comments (0)