0

I would like to filter the values of [name] from the array below.

Array
(
    [0] => Array
        (
            [name] => tags1
        )

    [1] => Array
        (
            [name] => tag2
        )

    [2] => Array
        (
            [name] => tag3
        )
)

How to do that?

3
  • 3
    What do you mean "filter"? Commented Feb 3, 2015 at 19:30
  • 1
    PHP version +5.5 ? -> array_column() OR look in the profile of @AbraCadaver for a workaround implementation for php versions under 5.5 :D Commented Feb 3, 2015 at 19:30
  • possible duplicate of PHP - get specific element from each sub array Commented Feb 3, 2015 at 19:34

3 Answers 3

1

If you just want to get all of the name values in an array:

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()

$names = array_column($array, 'name');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I keep that in mind. Unfortunately, my server runs only 5.3 at the moment.
0

If you are looking for simple solution you can use foreach loop:

foreach($array as $row){
    echo $row['name'];
}

2 Comments

That's awesome, thanks. How can I turn the result from the loop into a new array? (all found ['name'] values in one array)
instead of echo write $result[] = $row['name']. It will append new value to the $result array. Of course before foreach put $result = array();
0

I think you want to be able to filter your output array by a particular name? This function will return an array that only has the subarray that has the matching 'name'

function getspecificname($thisarray,$thisname){
    $arraytoreturn=array();
    foreach($thisarray as $onearray){
        if($onearray['name']==$thisname){
            $arraytoreturn[]=$onearray;
        }
    }
    return $arraytoreturn;
}

$myfilteredarray=getspecificname($yourarray,'tag2');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.