1

Hello I am fairly new to PHP and was wondering how can I find a specific token and token_time in the same array. For example, how can I find the token value 440745553780011a38b207466e2dae1a as well as the token_time value 1495672355 in the array below and have them displayed?

Array

array (size=1)
  'token' => 
    array (size=4)
      0 => 
        array (size=2)
          'token' => string '04a1dd0991b366fdc4d7d46fcff03cb3' (length=32)
          'token_time' => int 1495672339
      1 => 
        array (size=2)
          'token' => string '80d84dc863cbbeaef0c9a448f7865352' (length=32)
          'token_time' => int 1495672345
      2 => 
        array (size=2)
          'token' => string '440745553780011a38b207466e2dae1a' (length=32)
          'token_time' => int 1495672355
      3 => 
        array (size=2)
          'token' => string '766ac765d2a34e01cd954444d5895208' (length=32)
          'token_time' => int 1495672525
juice.gin
  • 71
  • 9

2 Answers2

2

Surprisingly, you can just simply use array_search() as you normally would but with an array:

$id = array_search([
    'token' => '440745553780011a38b207466e2dae1a',
    'token_time' => 1495672355
], $array['token']);

$id will contain the id of the array where both values are present. You can then access it like this:

$array['token'][$id];

The terms don't even need to be in the right order or type in the needle array:

$id = array_search([
    'token_time' => '1495672355', //passed as string, whereas array has these as ints
    'token' => '440745553780011a38b207466e2dae1a'
], $array['token']);
Enstage
  • 2,106
  • 13
  • 20
  • the problem with this solution is that if the arrays dont match element for element, search will fail. the question was to find specific token and token_time, presumably in arrays that may contain more than just "token" and "token_time". – user2914191 May 25 '17 at 02:30
1

Here is a function that accomplishes what you need:

function findToken(&$array, $token, $time){
    foreach($array['token'] as $data){
        if($data['token'] == $token && $data['token_time'] == $time){
            return $data;
        }
    }
    return null;
}

Here's how to use it:

$token = findToken($array, '440745553780011a38b207466e2dae1a', '1495672355');
if($token){
    echo "Found token";
} else {
    echo "Token not found";
}
user2914191
  • 877
  • 1
  • 8
  • 21