0

I've got a variable going like this(in the original list there no whitespace): http://www.iso.org/iso/list-en1-semic-3.txt

$country ="
ÅLAND ISLANDS;AX
ALBANIA;AL
ALGERIA;DZ
";

(going on and on in the same order)

I like to put this in a array going like this:

array:  [Åland Islands] ==> AX
        [Albania] ==> AL
        [Algeria] ==> DZ

I've try to use php explode but that doesn't work, my knowledge is to basic to get it right. Who can help?

 print_r(explode(';', $country));
1
  • first explode by lines ("\n") Commented Jul 13, 2011 at 2:04

3 Answers 3

2

This will get you where you're going:

$output = array();
// break it line-by-line
$lines = explode('\n', $country);
// iterate through the lines.
foreach( $lines as $line )
{ 
    // just make sure that the line's whitespace is cleared away
    $line = trim( $line );
    if( $line ) 
    {
        // break the line at the semi-colon
        $pieces = explode( ";", $line );
        // the first piece now serves as the index. 
        // The second piece as the value.
        $output[ $pieces[ 0 ] ] = $pieces[ 1 ];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
$result = array();
$lines  = explode(PHP_EOL, $country);

foreach ($lines as $line) {
    $line = explode(';', $line);
    $result[array_shift($line)] = array_shift($line);
}

Comments

0
$a = explode("\n", $country);
$result = array();
foreach($a as $line) {
    list($x,$y) = explode(";", $line);
    $result[$x] = $y;
}

Note: remove extra empty lines from $country or check for empty lines.

1 Comment

gives an "Notice: Undefined offset: 1 in" on the fourth line

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.