1

I have the following array:

array('data' => array('one' => 'first', 'two' => 'second'));

How i can get the value of key 'one' using string:

echo __('data.one');

function __($key) {
    $parts = explode('.', $key);
    $array = array('data' => array('one' => 'first', 'two' => 'second'));
    return ???;
}

Thank u!

2 Answers 2

3

Add your own error handling in case the key path isn't in your array, but something like:

$array = array('data' => array('one' => 'first', 'two' => 'second'));

$key = 'data.one';

function find($key, $array) {
    $parts = explode('.', $key);
    foreach ($parts as $part) {
        $array = $array[$part];
    }
    return $array;
}

$result = find($key, $array);
var_dump($result);
Sign up to request clarification or add additional context in comments.

Comments

1

This should work for you:

return $array["data"]["one"];

Also for more information and to learn a little bit see: http://php.net/manual/en/language.types.array.php
And : PHP - Accessing Multidimensional Array Values

EDIT:

This should work for you:

<?php

    $str = "data.one";
    $keys = explode(".", $str);
    $array = array('data' => array('one' => 'first', 'two' => 'second'));
    $access = $array;


    foreach($keys as $v)
        $access = $access[$v];

    echo $access;

?>

1 Comment

:) I need only by string 'data.one'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.