Skip to content
Advertisement

How can I add indexes to array instead of having keys start at zero?

I have an array but the key/indexing showing only zero for all the values instead of 0,1,2,3,4,5. When I print the array, it shows as

Array
(
    [0] => https://giphy.com/ladygaga
)
Array
(
    [0] => https://plus.google.com/+LadyGaga
)
Array
(
    [0] => https://twitter.com/ladygaga
)
Array
(
    [0] => https://www.facebook.com/ladygaga
)
Array
(
    [0] => https://www.instagram.com/ladygaga/
)

Here’s my code

foreach($social_media as $social){

    $typesocial = $social['type'];
    $val = array($social['url']['resource']);

    if ($social['type'] === 'social network') 
    {
        echo '<pre>'; print_r($val); echo '</pre>';
    }
}

Advertisement

Answer

I think you are looking for something like:

 foreach($social_media as $social){

    $typesocial = $social['type'];
    if($social['type'] === 'social network') {
      $host = parse_url($url, PHP_URL_HOST);
      $key = preg_match('#([a-z]*).[a-z]+$#', $host, $a);
      $valKey[$key] = $social['url']['resource'];
      $val[] = $social['url']['resource'];
    }

}
print_r($val);
print_r($valKey);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement