Skip to content

Instantly share code, notes, and snippets.

@Ider
Created March 3, 2014 19:36

Revisions

  1. Ider created this gist Mar 3, 2014.
    64 changes: 64 additions & 0 deletions idx.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    /**
    * Get value from $array with index or indics given by $keyOrKeys.
    * @param array $array The array to get value from.
    * @param mixed $keyOrKeys A single key, or a numeric array that contains multiple keys
    * to fetch from multidimensional array.
    * Key cound be either numeric or string.
    * If emtpy array given, the original $array will be returned.
    * @param mixed $default The default value to be returned if the array dose not contain
    * given key or midway value is not array type.
    * @return mixed The value that associated in $array.
    */
    function idx($array, $keyOrKeys, $default = null) {
    if (!is_array($keyOrKeys)) {
    $key = $keyOrKeys;
    return isset($array[$key])? $array[$key] : $default;
    }

    $keys = $keyOrKeys;
    $count = count($keys);

    $i = 0;
    while ($i < $count && is_array($array)) {
    $key = $keys[$i];
    if (!isset($array[$key])) {
    break;
    }
    $array = $array[$key];
    $i++;
    }

    if ($i == $count) {
    return $array;
    }

    return $default;
    }


    /*
    function idxTEST() {
    $a = array(0,1,2,3,4,
    'hello' => 'world',
    'a' => array(0,1,2,3,4,
    'welcome' => 'back'
    ),
    );
    echo '<pre>';
    // Test on single-index
    var_dump(idx($a, 0)); // 0
    var_dump(idx($a, 7)); // null
    var_dump(idx($a, 7, 7)); // 7
    var_dump(idx($a, 'hello')); // world

    // Test on multi-index
    var_dump(idx($a, array('a', 0))); // 0
    var_dump(idx($a, array('a', 7), 7)); // 7
    var_dump(idx($a, array('a', 'welcome'))); // back


    echo '</pre>';
    }

    idxTEST();
    */