1

I have a function that returns an array of default value types like so:

//////////////////////////////////////
// FUNCTION - CUSTOM FIELD TYPES
function customFieldTypes(){

  $types[1] = 'Textbox';
  $types[2] = 'Dropdown';
  $types[3] = 'Checkbox';
  $types[4] = 'Radio Button';


  // RETURN
  return $types;

} // END FUNCTION

I know you can loop through each without having to create an array to hold the values like:

foreach(customFieldTypes() as $type){

  // DISPLAY
  echo $type.' ';
}

would show Textbox Dropdown Checkbox Radio Button

my question is. Is there a way to go into that array without going

$arrayResult = customFieldTypes();
echo $arrayResult[2];

My only idea of doing this would be like:

echo customFieldTypes()[2];

but it give me a error saying unexpected '[', expecting ',' or ';'

is there anyway to do this? I do realize it's a shortcut but I was just wondering

Derek
  • 2,927
  • 3
  • 20
  • 33
  • 2
    `echo customFieldTypes()[2];` depending on the version of PHP you're running.... "Array Dereferencing" has been available since PHP 5.4.0 See [Example #7 in the PHP Docs](http://php.net/manual/en/language.types.array.php) – Mark Baker Jul 02 '15 at 18:17
  • @MarkBaker dang I'm using php 5.3.3 – Derek Jul 02 '15 at 18:22
  • `function customFieldTypes($i=null){ ... return $i ? $types[$i] :$types;` – splash58 Jul 02 '15 at 18:23
  • Then u will have to upgrade to `PHP 5.4` or > – Umair Ayub Jul 02 '15 at 18:24
  • You realise that even 5.4 is end-of-life apart from security patches now, and will be officially dead in just 2 months time – Mark Baker Jul 02 '15 at 18:24
  • @MarkBaker I know, I'm working for a company and they choose when they update so I can't do anything but thanks – Derek Jul 02 '15 at 18:27

1 Answers1

0

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

Example Array dereferencing

<?php
function getArray() {
    return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>

Just copied from here

Umair Ayub
  • 19,358
  • 14
  • 72
  • 146