1

I am in too much trouble. I need below type of array:-

$val = "abc";

$arr1["besk"] = $val
$arr2["besk"] = $val
     .    
     .
$arr15["besk"] = $val

I tried below:-

for($i = 1; $i<16; $i++)
{
   $arr.$i["besk"] = $val
}

here I've $val. so not to worry on that. But array is not properly creating. Any help would be appreciated.

5
  • if you don't mind kindly explain what is $var and val in your program. Commented Oct 14, 2017 at 5:23
  • and also updated your expected output for this program. Commented Oct 14, 2017 at 5:24
  • @kmgkumar check my edited question. Commented Oct 14, 2017 at 5:26
  • "I need below type of array" - no, more likely you just think that you do ... "numbered" variables names are almost always a sign that you should use an array in that place instead. Commented Oct 14, 2017 at 5:33
  • @Everybody Thanks for great and quick answer. As everybody have same answer so not able to accept anybody's. Again Thanks for giving me all of Your valuable time. Commented Oct 14, 2017 at 5:52

5 Answers 5

3

first define the array as string like

$arr = 'arr';

then use the foreach like

for($i = 1; $i<16; $i++)
  {
      ${$arr.$i}["besk"] = $val;
 }
Sign up to request clarification or add additional context in comments.

Comments

2

You need to use variable variables (not recommended)

for($i = 1; $i<16; $i++)
{
    ${"arr".$i}["besk"] = $val
}

EDIT : @CBroe is right about his comment, you should use an array instead. So the best solution would be to create a two dimensional array like so :

$arr = [];
for($i = 0; $i<15; $i++)
{
    $arr[$i]["besk"] = $val
}

The only difference is your array indexes start from 0 now and if you want to have the third value of your array you need this command $arr[2]["besk"]

Comments

1

it is very simple use this:

 for($i = 1; $i<16; $i++)
 {
      ${$arr.$i}["besk"] = $val
 }

Comments

1

Use this approach:

for($i = 1; $i<16; $i++)
{
    ${$arr.$i}["besk"] = $val;
}

Comments

1

add new variable

$val = "abc";
$arrName = "arr"; //this one
$arr1["besk"] = $val
$arr2["besk"] = $val
     .    
     .
$arr15["besk"] = $val

and to call it

for($i = 1; $i<16; $i++)
 {
      ${$arrName.$i}["besk"] = $val
 }

ps. you did not create array, you just create 15 array variable with 1 index("besk" index)

Comments

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.