0

My code reads a line from a file, splits the line into elements, and is supposed to put the elements in an array.

I used explode, but it does not put the elements into the array in sequential order.

Example: for input

line:   1000 3000 5000

This is what happens

$a=fgets($file); // $a= 1000 3000 5000
$arr= explode(" ",$a);
$u=$arr[3];    // $u=1000   
$w=$arr[6];    // $w=3000
$x=$arr[10];   // $x=5000

This is the desired order:

$u=$arr[0];    // $u=1000   
$w=$arr[1];    // $w=3000
$x=$arr[2];   // $x=5000

Why doesn't explode put data sequentially into the array?

1
  • what data are you getting in the other array parts? e.g. what is in array[0], array[1], array[2],array[4], etc... Commented Feb 16, 2012 at 18:59

3 Answers 3

1

It always puts them in sequentially. IF you are seeing this behavior then you must have extra in the document that are being exploded upon resluting in empty array elements. You will either need to pre-process the string or prune empty elements from the array.

Alternatively you could use preg_split with the PREG_SPLIT_NO_EMPTY setting.

Dome examples of that you are trying to do:

// using regex
$arr = preg_split("/ /", $a, PREG_SPLIT_NO_EMPTY);

// pruning the array
$arr = explode(" ", $a);
$arr = array_keys($a, '');
Sign up to request clarification or add additional context in comments.

2 Comments

is there any way to let the code know to ignore all the empty spaces between numbers in a line? Users create the original file and they can put one or more empty spaces between numbers. There is no restriction for users input in general.
Not with explode... you would have to use preg_split as i suggested for that or cleanup the string before using explode, or clean up the array after using it.
0

In your example, it's going to put a new array entry per every space.

To get what you're looking for, the returned string would have to be "$u=1000_$w=3000_$x=5000" (underscores represent spaces here)

Comments

0

An alternate way to do this would be to use array_filter to remove the empty elements i.e.

$arr = explode( ' ', $a ); // split string into array
$arr = array_filter( $arr ); // remove empty elements from array
$arr = array_values( $arr ); // strip old array keys giving sequential numbering, i.e. 0,1,2

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.