Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variables from array in PHP [closed]

I would like to get the values from this array into two variables:

  • $title
  • $url

for each of these inner arrays. How can I do it?

Array
(
[0] => Array
    (
        [0] => Reuters
        [1] => http://www.reuters.com
    )

[1] => Array
    (
        [0] => CNN
        [1] => http://www.cnn.com
    )
)
like image 948
urok93 Avatar asked Aug 28 '26 09:08

urok93


2 Answers

This would give you two arrays with your titles and urls:

foreach ($array as $value)
{
    $title[] = $value[0];
    $url[] = $value[1];
}

Or if you want to get your values into variables:

$title1 = $array[0][0];
$title2 = $array[1][0];

$url1 = $array[1][0];
$url2 = $array[1][1];
like image 105
Anas Avatar answered Aug 31 '26 00:08

Anas


While Anas' answer should work, I can't see the point of separating the data, because they obviously belong together (name & url is like horse and carriage, love and Marriage...)

$input = array(array('CNN','http://www.cnn.com'),array('rubbish','http://www.fox.com'));
$grouped = array();
while($pair = array_shift($input))
{
    $grouped[$pair[0]] = $pair[1];
}
echo $grouped['rubbish'];//echoes http://www.fox.com

Benefits of this approach?

  1. The original is redundant after processing, by shifting, you're freeing up memory (the array is being broken apart). So it's more efficient.
  2. Your data integrity is somewhat more guaranteed IMO (name and site stay paired).
  3. You can still get all names and all urls as separate, numerically indexed arrays if you want:

$title = array_keys($grouped);
$urls = array_values($grouped);
like image 21
Elias Van Ootegem Avatar answered Aug 31 '26 00:08

Elias Van Ootegem