0

I've very new to arrays and this is just beyond my understanding. How can I get the data out of this array and display it in an echo. I know this is an easy one! Thanks in advance! Here is the var_dump

array(2) { [0]=>  string(10) "John Smith" [1]=>  string(10) "Smithville" } 

and code below

$string = "John Smith Smithville";
$townlist = array("smithville", "janeville", "placeville");

function stringSeperation($string, $list)
{
    $result = array();

    foreach($list as $item)
    {
        $pos = strrpos(strtolower($string), strtolower($item));
        if($pos !== false)
        {
            $result = array(trim(substr($string, 0, $pos)), trim(substr($string, $pos)));
            break;
        }
    }

    return $result;
}

var_dump(stringSeperation($string, $townlist));

echo name

echo town

Regards, -Dan

6 Answers 6

3
$result = stringSeperation($string, $townlist);

echo $result[0]; // prints the name
echo $result[1]; // prints the town

or

foreach($result as $value) {
    echo $value;
}

Learn more about arrays.

Note: For linebreaks, you should either use PHP_EOL or <br /> depending on whether you want to generate HTML or not.

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

Comments

2
$strs = stringSeperation($string, $townlist);
echo $strs[0] . "\n";
echo $strs[1] . "\n";

Comments

2
$data = stringSeperation($string, $townlist);

$name = $data[0];
$town = $data[1];

echo $name;
echo $town;

Comments

1

echo arrayName[i]; where i is the index of the array you wish to output.

So in your case, echo $result[0]; will output name, echo $result[1]; will output town.

Comments

0

You can simply echo an element of the array if you know the key by doing this

echo $townlist[0]; //this will echo smithville

If you want to echo the whole array do this

$count = count($townlist)

for($i=0; $i<$count; $i++){
    echo $townlist[$i];
}

this will output

smithville
janeville
placeville

hope that helps you out!

Comments

0
$count = count($result);

for($counter = 0;$counter<$count;$counter++)
{
    echo $result[$counter];
}

or

foreach($result as $value) 
{
    echo $value;
}

Comments

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.