0

I'm looking for a way to find value in array compared to another one.

Let's assume we have a php array : (I take the one of this question because it's exactly my case)

$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'urlof40489'
    )
);

What's I need is to know if there's a way to find (for example) the value of name where uid is 100.

I hope to have been clear, thanks for your help :)

LittleBig
  • 145
  • 1
  • 4
  • 1
    Is there a way? Sure. You need to actually try though. Do a little research on accessing arrays and make an attempt. If you _have_ already tried something, please include your attempt in your question, along with the result and what debugging you've already done. – Patrick Q Jun 10 '19 at 13:16
  • 1
    Possible duplicate of [How to Get title by id in 2D array?](https://stackoverflow.com/questions/42508557/how-to-get-title-by-id-in-2d-array) – Rahul Jun 10 '19 at 13:43

2 Answers2

3

Yes There is a way,

$temp = array_column($userdb, 'name','uid');
echo ($temp[100] ?? ''); // php 7  
echo (!empty($temp[100]) ? $temp[100] : ''); // < php 7

array_column — Return the values from a single column in the input array

Syntax:

array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array

Demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60
  • 1
    Nice one (just comment it on aliveToDie post. I would check if the key (100) exist before echo it to avoid notice – dWinder Jun 10 '19 at 13:41
0

Unless I am overlooking something, this is as simple as iterating through the $userdb array, looking for the matching value in the uid field and then storing the resulting name in a variable:

$name = null;
foreach ($userdb as $user) {
    if ($user['uid'] == 100) {
        $name = $user['name'];
        break;
    }
}
var_dump($name);
Martin
  • 16,093
  • 1
  • 29
  • 48