array_?filter

Advertisement

Suppose you have an array:

$numbers = [ 10, 20, 30 ];

Now, You want to access each element to change its value.

E.g. Suppose you want to add 50 to each value and make an array-like.

$numbers = [ 60, 70, 80 ];

To do this you can use the php_filter() function.

E.g.

$numbers = [ 10, 20, 30 ];

$numbers = php_filter( function( $val ) {
     return $val + 50;
} );

// print_r( $numbers ); // Output [ 60, 70, 80 ]

Here, we have filtered each value of our array $numbers.

We have used the anonymous function here.

Alternatively, we can do the same with the below code:

$numbers = [ 10, 20, 30 ];

function increase_value( $val ) {
     return $val + 50;
}

$numbers = php_filter( 'increase_value' );

// print_r( $numbers ); // Output [ 60, 70, 80 ]

Syntax Syntax

php_filter()

The PHP syntac

%d bloggers like this: