Website Development Prices

Search Blog

Saturday, February 20, 2016

Spajanje i rastavljanje nizova (Joining and breaking arrays)

Pomocu funkcija implode i explode mozete vrsiti konverziju stringova u nizove i obrnuto. Funkcija implode sklapa niz na osnovu stringa, a funkcija explode rastavlja string u niz.

Ako zelite da sadrzaj niza stavite u string, mozete koristiti funkciju implode() i proslediti joj tekst koji treba da bude separator, u ovom primeru zarez.

Primer:

<?php

$motori[0] = "suzuki";
$motori[1] = "ducati";
$motori[2] = "ktm";

$tekst = implode(",", $motori);
echo $tekst;


?>

Rezultat:

suzuki,ducati,ktm

Objasnjenje: u ovom stringu nema razmaka izmedju stavki stringa, pa cemo separator promeniti na ", "

Nastavak primera 1:

<?php

$motori[0] = "suzuki";
$motori[1] = "ducati";
$motori[2] = "ktm";

$tekst = implode(", ", $motori);

echo $tekst;

?>

Rezultat:

suzuki, ducati, ktm

Ako zelite string da rastavite u niz, morate da ukazete na sta zelite da ga rastavite, na primer ", " i da to prosledite funkciji explode().

Primer 2:

<?php

$tekst = "suzuki, ducati, ktm";
$motori = explode(", ", $tekst);

print_r($motori);

?>

Objasnjenje: string smo rastavli u niz.

Rezultat:

Array ( [0] => suzuki [1] => ducati [2] => ktm )

Either via implode and explode you can make the conversion of strings to arrays and vice versa. The function implode is joining based on the string, and the function explode is breaking string to array.

If you want to place the contents of array into string, you can use function implode() and forward her the text that should be the separator, in this example, a comma.

Example:

<?php

$motorcycles[0] = "suzuki";
$motorcycles[1] = "ducati";
$motorcycles[2] = "ktm";

$text = implode(",", $motorcycles);

echo $text;

?>

Result:

suzuki,ducati,ktm

Explanation: this string has no spaces between the items of the string, so we will change the separator to ", ".

Continued example 1:

<?php

$motorcycles[0] = "suzuki";
$motorcycles[1] = "ducati";
$motorcycles[2] = "ktm";

$text = implode(", ", $motorcycles);

echo $text;

?>

Result:

suzuki, ducati, ktm

If you want to break the string in array, you have to point out to what you want to break it, for example, ", " and to forward it to function explode().

Example 2:

<?php

$text = "suzuki, ducati, ktm";
$motorcycles = explode(", ", $text);

print_r($motorcycles);

?>

Explanation: we broke string into array.

Result:

Array ( [0] => suzuki [1] => ducati [2] => ktm )

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.