Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first element in a multidimensional array?

I have the following array:

$extensions = array(
    '.info'     => array('whois.afilias.net','NOT FOUND'),  
    '.com'      => array('whois.verisign-grs.com','No match for'),
    '.net'      => array('whois.crsnic.net','No match for'),
    '.co.uk'    => array('whois.nic.uk','No match'),        
    '.nl'       => array('whois.domain-registry.nl','is free'),
);

How do I echo the '.com' or '.co.uk' (not the array that is inside the '.com' or '.co.uk', but just the TLD) without a foreach loop. echo $extensions['.com']; doesn't work, because that gives back: Array

EDIT: I want to select on the key itself not on the array number. Is this possible?

Thanks in advance!

like image 813
Guido Visser Avatar asked Nov 21 '12 09:11

Guido Visser


People also ask

How do you select the first element of an array?

Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

How do you get the first element in a two-dimensional list?

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows , an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list. Save this answer.

What is the first element in 2-D array?

The first element in a 2d array is at row 0 and column 0.


4 Answers

print_r(array_keys($extensions));
like image 169
Dogbert Avatar answered Nov 11 '22 05:11

Dogbert


php 5.4
echo array_keys($extensions)[0];

php 5.3
$keys = array_keys($extensions); echo $keys[0];

like image 43
Alex Avatar answered Nov 11 '22 06:11

Alex


if you want to just for 1 output

$arrext = array_keys($extensions);
print_r($arrext[0]);
like image 44
Jefri P. Avatar answered Nov 11 '22 07:11

Jefri P.


To echo the key is only necessary if they are unknowned. If you know the key, like you described in your question with: "echo $extensions['.com'];" you are probably better of just trying: echo ".com";

BUT if you don't know them and want to output for example the first one you could do like this:

<?php
$extensions = array(
    '.info'     => array('whois.afilias.net','NOT FOUND'),
    '.com'      => array('whois.verisign-grs.com','No match for'),
    '.net'      => array('whois.crsnic.net','No match for'),
    '.co.uk'    => array('whois.nic.uk','No match'),
    '.nl'       => array('whois.domain-registry.nl','is free'),
);
$keys = array_keys($extensions);
echo $keys[0]; //will output ".info"
?>
like image 21
etragardh Avatar answered Nov 11 '22 05:11

etragardh