0

I want to use variable string in Array like I saved array value any file or document or variable and I want to use it in array but I am failed to do so.

$var = "'title' => 'This is my title','name' => 'My name is John'";

$ar = array($var); 

echo $ar['title'].'<br>'.$ar['name'];

Error I am getting

Notice: Undefined index: title
Notice: Undefined index: name
1

2 Answers 2

1

You can use strtok() function for splitting a string into an array with a delimiter.

Try the below code:

<?php
  $var = "'title' => 'This is my title','name' => 'My name is John'";
  $ar = strtok($var,",");
  while ($ar!==false)
  {
    echo "$ar<br>";
    $ar=strtok(",");
  }
 ?>

Here I have used the "," as delimiter.

Output:

'title' => 'This is my title'

'name' => 'My name is John'

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah but I want to assign value of title and name in variable so I can use it anywhere like $mytitle = $var['title']; echo $mytitle; Output will be 'This is my title'
Please think that array is not a map to have the key value pair. What you are asking can not be achieved with Array.
0

Try this:

$ar = array('title' => 'This is my title','name' => 'My name is John');

2 Comments

I know I can do like this but I want to use variable and assume array value is saved in variable same like this no changing $var = "'title' => 'This is my title','name' => 'My name is John'";
$var is being stored as a single dimension value on 0th position. So if you echo out $ar[0] will give you the the $var value. You can use explode to get the array. explode(',', $var);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.