Skip to content

Instantly share code, notes, and snippets.

@prasanth22
Last active September 5, 2020 13:27
Show Gist options
  • Select an option

  • Save prasanth22/2de94eabdcba721540f0f2f9242b1c79 to your computer and use it in GitHub Desktop.

Select an option

Save prasanth22/2de94eabdcba721540f0f2f9242b1c79 to your computer and use it in GitHub Desktop.

Array_filter() :

<?php
class Post
{
    public $title;
    public $published;

    public function __construct($title, $published){
        $this->title = $title;
        $this->published = $published;
    }
}

$posts = [
    new Post('My First Post', true),
    new Post('My Second Post', true),
    new Post('My Third Post', false),
    new Post('My Fourth Post', true),
];

$unpublishedpPosts = array_filter($posts, function($post){
    return ! $post->published;
});

var_dump($unpublishedpPosts);

output:
array (size=1)
2 =>
object(Post)[3]
public 'title' => string 'My Third Post' (length=13)
public 'published' => boolean false


Array_map() :

$modified = array_map(function($post){
    return [ 'title' => $post->title ];
},$posts);

var_dump($modified);

output:
array (size=4)
0 =>
array (size=1)
'title' => string 'My First Post' (length=13)
1 =>
array (size=1)
'title' => string 'My Second Post' (length=14)
2 =>
array (size=1)
'title' => string 'My Third Post' (length=13)
3 =>
array (size=1)
'title' => string 'My Fourth Post' (length=14)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment