1

I want to call array variable inside the current array. Something like this:

$conv= array (
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => array_merge($conv['hello'])
);
print_r($conv['helo']);

How can I do this. thanks.

6
  • What is the expected output from your print_r? Commented Dec 9, 2017 at 17:28
  • My expected output is: Array ( [hello] => Array ( [0] => Hello [1] => Hi [2] => Hello, how are you? ) [helo] => Array ( [0] => Hello [1] => Hi [2] => Hello, how are you? ) ) thanks Commented Dec 9, 2017 at 17:36
  • So your helo is an exact copy of hello? Commented Dec 9, 2017 at 18:46
  • Yes bro. Its possible? Commented Dec 10, 2017 at 2:58
  • See my updated answer Commented Dec 10, 2017 at 8:40

2 Answers 2

2

If you want to define your function directly when you create the array, then you need to declare helo value as anonymous function, refer current array as global variable and return something you need

$conv = array(
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => function() {
        global $conv;
        return array_merge($conv['hello'], array("Bye", "See you"));
    }
);
print_r($conv['helo']());

Note that when you need the value returned from that function you need to call it as a function like above $conv['helo']() while calling just $conv['helo'] will return a Closure object.

UPDATE

According to what you're asking in comments, it seems that you just want to get a copy of hello value through a function

$conv = array(
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => function() {
        global $conv;
        return $conv["hello"];
    }
);
print_r($conv['helo']());
Sign up to request clarification or add additional context in comments.

3 Comments

Hello Drkey, Your solution is fine and may be work for me. But I want make it above way. is it possible? thanks
Sorry but I'm not sure I understood what exactly you mean with "above way". What do you expect to do and get?
That's, which I mentioned in the questions.
0

The way you try to build the array is probably impossible.
Because the array is not made untill the end of the function ; when you try to set 'helo', 'hello' is undefined.

You need to set 'hello' first then copy it to 'helo'.

$conv = array("hello" => array("Hello", "Hi", "Hello, how are you?"));

$conv["helo"] = $conv['hello'];
print_r($conv['helo']);

https://3v4l.org/PCJH7

2 Comments

Thank you vqdave could not get it right on my phone.
No problem, I have the same problem all the time!

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.