1

Pleas can you help if possible:

$xx_array = array(64,65,66,67);
.
.
.
foreach($xx_array AS $xx) {

Works perfectly but what I would like to do is:

$yy='5,6,7,8';

$xx_array = array($yy);
.
.
.
foreach($xx_array AS $xx) {

When I do this only first number is dealt with!?

The reason why I want it this way because I need same numbers in multiple array-s so I taught to have it in separate php file and just add include so I change only one file if needed!

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
  • 2
    Try `$xx_array = explode(",",$yy);` – Baba Dec 21 '12 at 18:33
  • What does this have to do with [tag:mysql] and [tag:sql]? Are you storing delimited strings in a relational database? [You really shouldn't do that](http://stackoverflow.com/a/3653574). – eggyal Dec 21 '12 at 18:34
  • Removed the unnecessary tags from this post. Reason; Your question mentions nothing to do with database interaction – Daryl Gill Dec 21 '12 at 18:41
  • Sorry the reason I included mysql is that the whole script (which is not shown here)is involved in inserting or inputting data in DB! – Internet caffe Dec 21 '12 at 18:49
  • @Internetcaffe: Can you be more explicit? As I said, you *really* shouldn't store delimited strings of this sort in your database. – eggyal Dec 21 '12 at 21:15

5 Answers5

7

Use explode:

$yy='5,6,7,8';
$xx_array = explode(',', $yy);

http://php.net/manual/en/function.explode.php

Petah
  • 45,477
  • 28
  • 157
  • 213
  • 2
    Wouldn't this create a multi-dimentional array as explode() returns an array and you're putting it inside array()? – kittycat Dec 21 '12 at 18:36
  • It seems to work as a charm :) Is there a limit on number of numbers or number of digits (1,100,10000,1000000) – Internet caffe Dec 21 '12 at 18:57
  • @Internetcaffe it is only limited by your available memory. http://php.net/manual/en/ini.core.php#ini.memory-limit – Petah Dec 22 '12 at 09:26
4

Use explode:

$xx_array = explode(',', $yy);
Emil Aspman
  • 996
  • 1
  • 17
  • 26
4

$yy is set as a string for 5,6,7,8.. To Get this string you will need to use explode(); which will turn that string into an array.

$xx_array = explode(',', $yy);

See the manual:

http://uk1.php.net/manual/en/function.explode.php

Example:

<?php
$yy = '5,6,7,8';

$xx_array = explode(',', $yy);
print_r($xx_array);
?>

The print_r(); Will Return:

Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 ) 

Which is what you are looking for

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
3

Using explode:

$xx_array = explode(",", $yy);

Which automatically breaks apart your string by "," and creates an array

Sharlike
  • 1,789
  • 2
  • 19
  • 30
1

Here's the answer to your question:

$yy='5,6,7,8';

$xx_array = array($yy);

foreach($xx_array AS $xx) {

$yy isn't an actual array itself. It's just a string. So $yy needs to become an array. Yes you can use the explode or you can do this:

$yy = array('5', '6', '7', '8');

Now $yy is truly an array.

MrTechie
  • 1,797
  • 4
  • 20
  • 36