-5

Lets assume, the return value of an search-fuction is something like this

// If only one record is found
$value = [
  'records' => [
    'record' => ['some', 'Important', 'Information']
  ]
]

// If multiple records are found
$value = [
  'records' => [
    'record' => [
       0 => ['some', 'important', 'information'],
       1 => ['some', 'information', 'I dont care']
    ]
  ]
]

what woul'd be the best way to get the important information (in case of multiple records, it is always the first one)?

Should I check something like

if (array_values($value['record']['records'])[0] == 0){//do something};

But I guess, there is a way more elegant solution.

Edit: And btw, this is not realy a duplicate of the refered question which only covers the multiple records.

  • Right @Uchiha and explain your query in detail. Not getting exactly what you want. – Kausha Mehta Oct 16 '15 at 10:03
  • return value should be the ['some', 'important', 'infomation']. – Matthias Moritz Oct 16 '15 at 10:06
  • 2
    Possible duplicate of [Get the first element of an array](http://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array) – marian0 Oct 16 '15 at 10:07
  • Ok, getting now. You can check it like this `if(is_array($value['records']['record'][0])) { $new_array=$value['records']['record'])[0]; } else { $new_array=$value['records']['record']; }` – Kausha Mehta Oct 16 '15 at 10:09

2 Answers2

0

check like this..

if(is_array($value['records']['record'][0])) {
    // multiple records
} else {
    // single record
}
Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
0

If you want the first element of an array, you should use reset. This function sets the pointer to the first element and returns it.

$firstValue = reset($value['record']['records']);

Edit.. after reading your question again, it seems, you dont want the first element. You rather want this

if (isset($value['record']['records'][0]) && is_array($value['record']['records'][0])) {
    // multiple return values
} else {
    // single return value
}

Doing this is kind of error proun and i wouldn't suggest that one function returns different kinds of array structures.

Philipp
  • 15,377
  • 4
  • 35
  • 52