Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove key from returned array (using array_filter)

I have array_filter functions that returns this:

Array(1) {
  [3]=>
  object(Timber\Term)#5173 (16) {
    ["PostClass"]=>
    string(11) "Timber\Post"
    ["TermClass"]=>
    string(4) "Term"
    ["object_type"]=>
    string(4) "term"
    ["_children"]=>
    NULL
    ["name"]=>
    string(24) "Installation Maintenance"
    ["taxonomy"]=>
    string(8) "category"
    ["id"]=>
    int(73)
    ["ID"]=>
    int(73)
    ["term_id"]=>
    int(73)
    ["slug"]=>
    string(24) "installation-maintenance"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(73)
    ["parent"]=>
    int(39)
    ["count"]=>
    int(1)
    ["filter"]=>
    string(3) "raw"
    ["term_order"]=>
    string(1) "0"
  }
}

What I want is to remove key from array [3](sometimes is different number for key) and get the value.
Tried flattening array but that didn’t work, maybe because value is object?

Function that return that array is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$filter = array_filter($arr, 
  function($item) use ($slug) {
    return $item->slug == $slug;
  }
);

Edit: Trying to clarify what I want to achieve. Srry if I wasn’t from the start.

Is it possible to return only object so I can type something like
$filter->name and not $filter[0]->name;

So this is the data I want:

Object {
  object(Timber\Term)#5173 (16) {
    ["PostClass"]=>
    string(11) "Timber\Post"
    ["TermClass"]=>
    string(4) "Term"
    ...
}

>Solution :

Instead of doing array_filter (that always returns array of items), you should just use simple foreach.

// @lang PHP8

private function findItem(array $items, string $slug): ?\Timber\Term
{
    foreach ($items as $item) {
        if ($item->slug === $slug) {
            return $item;
        }

        return null;
    }
}

$item = $this->findItem($items, $someSlug);

echo $item->slug ?? throw new \Exception("No item found with slug '{$slug}'");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading