Php, separate words and save variables?

1

Hello I hope you can help me try to be specific: What I want is to separate words stored in a variable and save them in individual variables: example:

$cadena="Hola mundo"; 

What I want is something like this:

$palabra1="hola"; 
$palabra2="mundo"; 

Thank you I count on you ... Note! My main string only has 2 words.

    
asked by Wilson Cajisaca 13.07.2017 в 08:19
source

2 answers

2

If you only have two words, you can easily do it this way:

<?php

    $cadena = 'Hola Mundo';

    list($palabra1, $palabra2) = explode(' ', $cadena);

    echo $palabra1 . '<br>';

    echo $palabra2 . '<br>';

We go in parts:

explode takes a separator element (in our case ''), and use it to divide a string and store the result in an array. Since we have "Hello World", this will generate an array with indexes 0 = > "Hello", 1 = > "World".

list is a php language construction, takes indexes of an array and stores them in a list of variables passed as arguments. The first element of the array is stored in the first variable, and so on.

    
answered by 13.07.2017 / 08:24
source
1

Use the explode function that stores the words in an array

$arrayPalabras = explode(" ",$cadena);

API of the php explode function

    
answered by 13.07.2017 в 08:23