0

Given the following structure:

Array
(
    [0] => Array
        (
            [id_field] => 100
        )

    [1] => Array
        (
            [id_field] => 200
        )

    [2] => Array
        (
            [id_field] => 382
        )

    [3] => Array
        (
            [id_field] => 509
        )

    [4] => Array
        (
            [id_field] => 636
        )

    [5] => Array
        (
            [id_field] => 763
        )

    [6] => Array
        (
            [id_field] => 890
        )

    [7] => Array
        (
            [id_field] => 1017
        )

)

Is there a built in array method which can grab all id_field values?

I can loop over them for sure, but think maybe there is a built in that i cannot see in the manual that already does this?

3 Answers 3

2

If you have PHP 5.5.0+, you could use array_column():

$result = array_column($data, 'id_field');

If you're running an older PHP version, you can use the userland implentation of this function (written by the same author who wrote the original array_column() function).

However, for simple use-cases, this can be implemented as function using a simple foreach loop. This isn't guaranteed to handle all possible cases, but it should be enough for the most part.

function array_column2(array $arr, $column) {
    $result = array();
    foreach ($arr as $key => $value) {
        $result[] = $arr[$column];
    }
    return $result;
}
Sign up to request clarification or add additional context in comments.

Comments

0

using array filtering:

function id($var){
    return($var['id_field']);
}

print_r(array_filter($arr,"id"));

or in PHP 5.4+

print_r(array_filter($arr,  function id($var){
    return($var['id_field']);
}));

Comments

0

array_keys() is what you are looking for.

sample from docs:

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

and it's output:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

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.