PDA

View Full Version : multidimensional array from a variable


tony09uk
07-11-2012, 10:00 PM
I am trying a few exercises and my latest one is to remove the websites extensions, so I'm just left with the sites name then make a multidimensional array from those values.Then using a loop, add new elements with keys and values.

My problem is:
How do put those values into an array?

I have made this for part one of the excercise

$sites = array();
$sites[] = "http://www.facebook.com/";
$sites[] = "http://www.argos.co.uk/";
$sites[] = "http://www.next.co.uk/";
$sites[] = "http://www.halfords.com/";
$sites[] = "https://twitter.com/";
$sites[] = "http://www.comet.co.uk/";

$remove = array("http://www.", "https://", ".co.uk/", ".com/");

foreach($sites AS $k => $v){
$taken = str_replace($remove, "", $v);
echo ucfirst($taken) . "<br/>";
}
**outputs**

Facebook
Argos
Next
Halfords
Twitter
Comet

**outputs**

I have tried putting another foreach loop inside the one I have, I have also tried creating an empty array before running the first loop, im guessing im close to the answer but i cant work it out at the moment.

tony09uk
07-11-2012, 10:11 PM
Ive managed to place the values into an array

$sites = array();
$sites[] = "http://www.facebook.com/";
$sites[] = "http://www.argos.co.uk/";
$sites[] = "http://www.next.co.uk/";
$sites[] = "http://www.halfords.com/";
$sites[] = "https://twitter.com/";
$sites[] = "http://www.comet.co.uk/";

$remove = array("http://www.", "https://", ".co.uk/", ".com/");

$newarray = array();
foreach($sites AS $k => $v){
$taken = str_replace($remove, "", $v);
echo ucfirst($taken) . "<br/>";
array_unshift($newarray, ucfirst($taken));
}
print_r($newarray);

Now I will get started on the next part :)

is there a better way to do this or is this an acceptable way?