0

I want to make an array in PHP but it should be in specific format such this:

array(1, 5, 3)

I mean, I have the values 1, 5 and 3 from my database, so I had to loop it with the use of array_push

$a=array();

foreach( $db_nums as $db_num ){
array_push($a, $db_num);
}

print_r($a);

but it outputs:

Array ( [0] => 1 [1] => 5 [2] => 3 );

i want it to be only:

array(1, 5, 3 );

Any ideas how? Thanks a lot for any help!

10
  • 1
    I don't really understand your question? How do you mean in a specific format. Commented Mar 21, 2012 at 5:55
  • You're maybe looking for var_export? (php.net/var_export) Otherwise, no idea. Commented Mar 21, 2012 at 5:57
  • did you mean that the elements should be in ascending order? Commented Mar 21, 2012 at 5:57
  • all you need is $myarray = array(1,2,3) and you done with php Commented Mar 21, 2012 at 5:57
  • 1
    its not an array if there are no keys. array(1, 5, 3 ); is the same as Array ( [0] => 1 [1] => 5 [2] => 3 ); if you don't specify the keys php does it for you starting at 0 Commented Mar 21, 2012 at 6:12

3 Answers 3

2

Just use the below code:

$Array = array(1,2,3);

Edit:

$a = array();

foreach( $db_nums as $db_num )
{
    $a[] = $db_num;
}

print_r($a);
Sign up to request clarification or add additional context in comments.

Comments

0
$db_nums = array(1, 2, 3); //pointless example, but comes from DB
$a = array();
foreach ($db_nums as $n) {
    $a[] = $n;
}
var_export($a);

That will output:

array (
  0 => 1,
  1 => 2,
  2 => 3,
)

Which is about as close as you're going to get without writing your own function to do it.

(Also note that in this example, you could just directly do var_export($db_nums).)

Comments

0
<?php  $array = array("foo", "bar", "hallo", "world");  var_dump($array); ?>

You can use that

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.