1

Given the following array and a given id, how can I return the corresponding elem? For instance, given id=6, it should return goodby. The id values are the PKs from a database, thus will always be unique.

Obviously, I could just iterate over the first array, check the values, and break and return the elem upon match, but I expect there is a much more elegant way to do this.

array(
    array('id'=>2,'elem'=>"hello"),
    array('id'=>6,'elem'=>"goodby"),
    array('id'=>8,'elem'=>"goodnight")
);
2

4 Answers 4

1

A basic alternative to consider would be to collect the columns with array_column (indexed by the id column) and then dereferencing the array to access the passed index value $id, something like:

$myArray = array(
    array('id'=>2,'elem'=>"hello"),
    array('id'=>6,'elem'=>"goodby"),
    array('id'=>8,'elem'=>"goodnight")
);

function getValue($id, $a)
{
    return array_column($a, 'elem', 'id')[$id];
}

var_dump(getValue(6, $myArray));

Enhancing the proof to get more control:

function getValueAlternative($where, $get, $fromSource)
{
    $where = explode("=", $where);

    return array_column($fromSource, $get, $where[0])[$where[1]];
}

var_dump(getValueAlternative("id=2", "elem",  $myArray));
var_dump(getValueAlternative("elem=hello", "id",  $myArray));
Sign up to request clarification or add additional context in comments.

Comments

0

See this :

myfunction($products, $needle)
{
   foreach($products as $key => $product)
   {
      if ( $product['id'] === $needle )
         return $key;
   }
   return false;
}

Similar : PHP Multidimensional Array Searching (Find key by specific value)

Comments

0

Why don't you use the following structure?:

array(
    2 => array('elem'=>"hello", ...),
    6 => array('elem'=>"goodby", ...),
    8 => array('elem'=>"goodnight", ...)
);

Then you could access them like:

$array[$id];

You told that you've used PDOStatement::fetchAll() to obtain your array. You can tell fetchAll() to return a structure like I've suggested, you need to use the fetch mode PDO::FETCH_GROUP:

$pdo->query('SELECT * FROM table')->fetchAll(PDO::FETCH_GROUP);

Well defined data structures are the essential basics of a good program. In your case an associative array having the ids as their keys and the whole records as the value portion,will be better than a numeric array as it allows you to perform fast, id based access. Of course you have to pay for this - with a little more memory.

6 Comments

Was wondering the same thing. Though suspected it may be (based on the id) a returned array for somewhere, though they could still edit the initial return.
Because the array doesn't have that structure and the data is returned using fetchall.
You can customize the style how fetchAll will return the array.. I think to remember that their is something. If not, then simply use fetch().. fetchAll() makes no sense at all in the most cases.
@hek2mgl I didn't know I could style fetchAll to put the PK as the array key. Do you know for sure whether it is possible? Thanks
@user1032531 Its PDO::FETCH_GROUP
|
0

You could use the array_search PHP function:

    /**
     * @param array $array
     * @param int $id
     * @return string|null
     */
    function getElem(array $array, $id) {
        foreach($array as $subArr) {
            if(($key = array_search($id, $subArr, true)) !== false) {
                if(strcmp($key, "id") === 0) {
                    return $subArr['elem'];
                }
            }
        }
        return null;
    }
    $array = array(
            array('id'=>2,'elem'=>"hello"),
            array('id'=>6,'elem'=>"goodby"),
            array('id'=>8,'elem'=>"goodnight")
        );
    echo getElem($array, 6);

1 Comment

How do you think this compares to Hors Sujet's solution?

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.