Jump to content

Adding a key to elements of a string that has been split.


coolman1985

Recommended Posts

Ok I have an array called $files, which is the result of reading files from a folder.

Example 1.txt, 2.txt, 3.txt and so on. I have used the split function on that array because I want a new array that contains only the numbers of the $files array.

 

for($b = 2; $b <= 16; $b++){

  $string = split("\.",$GLOBALS['files'][$b]);

    echo $string[0]

}

 

echo $string[0]; //will show 123

 

The problem is I want to be able to do somthing like

echo $string[0][0];// and show 1

echo $string[0][1];// and show 2

echo $string[0][2];// and show 3

 

This should be easy but I cant get it, please help:)

yes

 

foreach($GLOBALS['files'] AS $file){

   $nums[] = substr($file, 0, strpos($file, '.'));

   echo $nums[2];

}

 

had to start $nums on 2 because my $files array Includes . and  .. because of the directory. Why , however is the number repeated multiple times. For example the code above shows the result 111111111111. there are 12 ones, it probably has somthing to do with the 13 files i have in the file im reading from.

 

Thank you for your help.

Because you're echoing the one at number 2 over and over, not starting at two. Try this:

 

$files = $GLOBALS['files'];

$files = array_shift(array_shift($files));

foreach($files AS $file){

  $nums[] = substr($file, 0, strpos($file, '.'));

}

Warning: array_shift() [function.array-shift]: The argument should be an array in C:\Program Files\xampp\htdocs\xampp\delete.php on line 83

 

Warning: Invalid argument supplied for foreach() in C:\Program Files\xampp\htdocs\xampp\delete.php on line 84

 

ok im stupid, the code you gave the first time works great

 

foreach($GLOBALS['files'] AS $file){

  $nums[] = substr($file, 0, strpos($file, '.'));

}

 echo $nums[2];// why did i put it inside the foreach loop? stupid :D

 

thank you

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.