0

I am fetching records from mysql database through while loop.

$sql=mysql_query("SELECT * FROM animate ORDER BY RAND() LIMIT 10") or die("query Field");

 while($row=mysql_fetch_array($sql)){

$row['code'];

 }

output is xyacefg.

Now I want to break this output into an array I want to place each letter into separate index of array like

array('x','y','a','c','e','f','g');

I have used explode

$array = explode(' ', $row['code']);

but it didnot work. now the final code is .

$sql=mysql_query("SELECT * FROM animate ORDER BY RAND() LIMIT 10") or die("query Field");

 while($row=mysql_fetch_array($sql)){

$row['code'];

 }

$array = explode(' ', $row['code']);
3
  • Have you echoed it out? echo var_dump($row['code']); Commented Apr 15, 2016 at 17:17
  • 1
    Read about using arrays in PHP. Commented Apr 15, 2016 at 17:18
  • $array[] = str_split($row['code']) inside the loop, print_r($array) outside the loop Commented Apr 15, 2016 at 17:19

3 Answers 3

2

You need to create an empty array and assign value to them like below:-

$new_array = array(); // create a new array
$sql=mysql_query("SELECT * FROM animate ORDER BY RAND() LIMIT 10") or die("query Field");

 while($row=mysql_fetch_array($sql)){

    $new_array[] = $row['code']; // assign value to array

 }
echo "<pre/>";print_r($new_array); // print array which is created

Note:- My assumption is $row['code'] giving you value one-by-one because it is in while loop.

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

1 Comment

Nope, this seems to be the correct answer, rather than the (current) top. @Anant
2

Its easy with str_split:

<?php
$array = str_split("xyacefg"); //In your case: str_split($row['code']);
print_r($array);

Output:

Array
(
    [0] => x
    [1] => y
    [2] => a
    [3] => c
    [4] => e
    [5] => f
    [6] => g
)

Comments

0

Just use str_split() function. If you want to get exact same result as you want like:

array('x','y','a','c','e','f','g');

then use following code:

<?php
  $string = "xyacefg";
  $exploded = str_split($string);
  echo 'array("'.implode('", "', $exploded).'");';
?>

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.