Reputation: 2309
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!
Upvotes: 7
Views: 25390
Reputation: 134
You can simply use array_key_first (PHP 7 >= 7.3.0, PHP 8).
$firstExtensionKey = array_key_first( $extensions );
$firstExtension = $extensions[ $firstExtensionKey ];
Upvotes: 0
Reputation: 869
You could also the reset() function, which returns the first item in an array (and resets its internal pointer to the first element).
$keys = array_keys($extensions);
$first = reset($keys);
Upvotes: 1
Reputation: 14478
In case it helps someone else, you can also 'shorthand' this to something like :
echo array_keys($extensions)[0];
Upvotes: 0
Reputation: 4834
I think what you really wanted is key($extensions)
, the problem is that you can't pick the array position with key(), so you have to either use a loop or assign all the keys into a new array like the other solutions.
The only ways to move the pointer is using next()
, prev()
, reset()
or end()
, which moves the pointer 1 position to the left/right on the array, or the array's first/last element
Upvotes: 0
Reputation: 71
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"
?>
Upvotes: 1
Reputation: 4221
Using array_keys will grab all the keys for you.
For example,
$array = array_keys($extensions);
Then you can simply call
print $array[0]; //displays .info
echo $array[1]; // displays .com
echo $array[2]; // displays .net
Upvotes: 0
Reputation: 76
if you want to just for 1 output
$arrext = array_keys($extensions);
print_r($arrext[0]);
Upvotes: 1
Reputation: 12049
php 5.4
echo array_keys($extensions)[0];
php 5.3
$keys = array_keys($extensions); echo $keys[0];
Upvotes: 5