0

I am working on my PHP script to fetch the strings by using explode so I can store the strings into the array. I have got a problem with my code because when I split the strings to store them into the array, I will get like this:

Array ( [0] => [1] => 0.1 noname.gif [2] => 0.2 what-is-bootstrap.png )

Here is what it should be:

Array ( [0] => 0.1 noname.gif [1] => 0.2 what-is-bootstrap.png)

Here is what it show in the results:

attid: 0.1 filename: noname.gif
attid: 0.2 filename: what-is-bootstrap.png

Here is the code:

<?php

$attached = 'attid: 0.1 filename: noname.gif
attid: 0.2 filename: what-is-bootstrap.png';
$attached_files = explode('attid:', $attached);
$attached_files = str_replace('filename:', '', $attached_files);

?>

I don't know how to store the strings into the array with each key like 0 and 1.

Can you please show me an example how I can store the strings into the array when I split the strings?

0

1 Answer 1

2

If you add the following line...

$attached_files = array_values(array_map('trim', array_filter($attached_files)));

it will do 3 things.

The array_filter() will remove any empty lines. The reason for the first one is that as you explode() on 'attid:', it will consider there to be a value before the first occurrence - which is blank. You could just do array_shift() to remove the first item, but array_filter() will filter any empty lines.

Secondly - you will find there are trailing new lines etc. So the array_map() with trim will ensure any excess whitespace is removed.

Lastly array_values() will re-index the array to start from 0.

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

5 Comments

Thank you very much for this, so in which line I should add the code that come with array_map?
Add it anywhere after the line with explode(). Although it would ideally be just after as it would ensure that empty lines are removed before any other processing is done.
Ok, thank you. I'm getting this Array ( [1] => 0.1 noname.gif [2] => 0.2 what-is-bootstrap.png ), so how I can set the key that start with 0 instead of 1?
Added array_values() to re-index the array.
Thank you very much for this as this is what I am looking for exactly!

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.