0

I have the two following variables:

$contact_number=array('0123456','65321');
$msg="My Text" ;

I am trying to create an array like following using the above variables

$myarray =array(
       array("0" => "0123456", "1" => "My Text"),
       array("0" => "65321", "1" => "My Text")
 );

I have tried the following code but it is not creating the exact array live above:

for($i=0; $i < count($contact_number); $i++ ) {
      $myarray[] =array(array("0" =>$contact_number[$i], "1" =>$msg),);
  }

 var_dump($myarray); 

Could you please tell me how to solve this problem

3 Answers 3

1

You can loop through every contact number, and append a message like this:

$contact = array('0123456','65321');
$message = "My Text" ;

$array = array();

foreach($contact as $value) {
    $array[] = array($value, $message);
}

var_export($array);

Produces this:

array (
  0 => 
  array (
    0 => '0123456',
    1 => 'My Text',
  ),
  1 => 
  array (
    0 => '65321',
    1 => 'My Text',
  ),
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your answer and making the code easier/smarter :)
1

You just need to append the new array values:

  $myarray[] = array("0" => $contact_number[$i], "1" => $msg);

The double nesting array( array(0=>.., 1=>..) ) was redundant, because assigning using $array[] = already creates a new subarray.

See http://php.net/manual/en/language.types.array.php#~square+bracket+syntax

Comments

0
$contact_number=array('0123456','65321');
$msg="My Text" ;

foreach($contact_number as $key => $number) {
    $my_array[] = array($key => $number, $key+1 => $msg);
}
var_dump($my_array);

the above will result

array (size=2)

0 =>

array (size=2)

  0 => string '0123456' (length=7)

  1 => string 'My Text' (length=7)

1 =>

array (size=2)

  1 => string '65321' (length=5)

  2 => string 'My Text' (length=7)

screw my internet connection, someone already answered ..

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.