Php array getting first element

Get first value of an array [duplicate]

This function sets the internal pointer of the array to first element and also returns it.

Also is more optimal than array_keys as if the array contains for example 1000 values, array_keys would generate an array of 1000 positions just to get the first element, with reset you Will not generate extra unused data that consumes memory.

Thanks. Almost got it, but it’s looking now like this ‘Array ( [0] => Pen, [1] => Apple )’ And I need to get ‘Array ( [0] => Array ( [0] => Pen) [1] => Array ( [0] => Oooo ))’

Sorry. Array ( [0] => Pen, [1] => Apple ) And I need to get Array ( [0] => Array ( [0] => Pen ) [1] => Array ( [0] => Oooo ) )

You can use array_column function

$array = array( array('Pen', 'Apple' ), array('Oooo', 'Pineapple pen') ); $result = array_column($array, 0); echo '
'; print_r($result); echo '

';

$param = array('first_key'=> 'First', 2, 3, 4, 5); $keys = array_keys($param); echo "Key Key = ".$keys[0]; echo '
'; print_r("Key mt24"> 
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Oct 22, 2016 at 13:49
answered Oct 22, 2016 at 13:40
Add a comment |
0

Try:

$result = array(); foreach ($elements as $elem)

Источник

PHP get first array element [duplicate]

How can i get only the first element [0]'s data (as in backdrop_path, original_title, etc etc)? I'm new at PHP arrays :). And of course this is what i used to output my array data:

6 Answers 6

Returns the value of the first array element, or FALSE if the array is empty.

The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns FALSE.

You can point to the array with this $theMovie['result'][0]['backdrop_path']; or you can loop through it like this,

foreach($theMovie['results'] as $movie)

I'm not getting any data back from the code above BUT i am getting data back with the $theMovie['result'][0]['backdrop_path'];??

You can use array_shift to pop off the first element, then check that it is valid ( array_shift will return null if there are no results or the item isn't an array).

$data = array_shift($theMovie['results']); if (null !== $data) < // process the first result >

If you want to iterate though all the results, you can do a foreach loop while loop with array_shift .

foreach($theMovie['results'] as $result) < echo $result['backdrop_path']; >while ($data = array_shift($theMovie['results']))

Or just use $theMovie['result'][0]['backdrop_path']; as already suggested, after checking that $theMovie['result'][0] is actually set.

Assuming all this code is stored in a variable $datas :

$results = $datas['results']; $theMovie = $results[0]; 

But keep in mind this produces errors when the result array is empty.

To start learning a bit I would suggest that you use: array_slice

Now your code in PHP would look like:

$myVariable = [ "page" => 1, "results" => [ [ 'adult' => 1, 'backdrop_path' => "/gM3KKixSicG.jpg", 'id' => 603, 'original_title' => "The Matrix", 'release_date' => "1999-03-30", 'poster_path' => "/gynBNzwyaioNkjKgN.jpg", 'popularity' => 10.55, 'title' => "The Matrix", 'vote_average' => 9, 'vote_count' => 328, ], [ 'adult' => 2, 'backdrop_path' => "/gM3KKixSicG.jpg", 'id' => 603, 'original_title' => "The Matrix Revolutions", 'release_date' => "1999-03-30", 'poster_path' => "/gynBNzwyaioNkjKgN.jpg", 'popularity' => 10.55, 'title' => "The Matrix Revolutions", 'vote_average' => 9, 'vote_count' => 328, ], ], ]; 

Then on the above one you use:

$newArray = array_slice($myVariable['results'], 0, 1); 

The output of the command above would be:

[ [ "adult" => 1, "backdrop_path" => "/gM3KKixSicG.jpg", "id" => 603, "original_title" => "The Matrix", "release_date" => "1999-03-30", "poster_path" => "/gynBNzwyaioNkjKgN.jpg", "popularity" => 10.55, "title" => "The Matrix", "vote_average" => 9, "vote_count" => 328, ], ] 

Now if you want to get a flat array, because above one is still multidimensional, you simple use:

[ "adult" => 1, "backdrop_path" => "/gM3KKixSicG.jpg", "id" => 603, "original_title" => "The Matrix", "release_date" => "1999-03-30", "poster_path" => "/gynBNzwyaioNkjKgN.jpg", "popularity" => 10.55, "title" => "The Matrix", "vote_average" => 9, "vote_count" => 328, ] 

OR if you want one liner with array_slice add index 0 at the end of the command:

$newArray = array_slice($myVariable['results'], 0, 1)[0]; 

Источник

get first and last element in array

Have a look at reset() and end() . P.S. 0 will always be the 1st element, and for the last you can do $arr[count($arr)-1] .

6 Answers 6

reset() : Returns the value of the first array element, or FALSE if the array is empty.

end() : Returns the value of the last element or FALSE for empty array.

NOTE: This will reset your array pointer meaning if you use current() to get the current element or you've seeked into the middle of the array, reset() and end() will reset the array pointer (to the beginning and to the end):

yeah but take a look at my array, when i use your code, i get: "Warning: reset() expects parameter 1 to be array, null given" and the same for end()

You can accessing array elements always with square bracket syntax. So to get the first use 0 , as arrays are zero-based indexed and count($arr) - 1 to get the last item.

$firstEle = $arr[0]; $lastEle = $arr[count($arr) - 1]; 

As of PHP 7.3, array_key_first and array_key_last is available

$first = $array[array_key_first($array)]; $last = $array[array_key_last($array)]; 

You can use reset() to get the first:

reset() rewinds array's internal pointer to the first element and returns the value of the first array element.

end() advances array's internal pointer to the last element, and returns its value.

For first element: current($arrayname);

For last element: end($arrayname);

current(): The current() function returns the value of the current element in an array. Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

end(): The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods: current() - returns the value of the current element in an array

$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6); $first = current($array); $last = end($array); echo 'First Element: '.$first.' :: Last Element:'.$last; 

Output result:

First Element: 24 :: Last Element:24.6 

Источник

How to Get the First Element of an Array in PHP?

Get First Element of an Array With Sequential Numeric Indexes

It's fairly easy and straightforward to get the first element of a sequential array in PHP. Consider for example the following array:

$sequentialArray = ['foo', 'bar', 'baz'];

Accessing the First Element of Array Directly:

echo $sequentialArray[0] ?? ''; // output: 'foo'

By using ?? (the null coalescing operator) you can return the first index if it's set and not null, or return an empty string otherwise.

Using list() :

// PHP 4+ list($first) = $sequentialArray; // or, alternatively in PHP 7.1+ [$first] = $sequentialArray; echo $first; // output: 'foo'

For a non-sequential array this would throw an error because list() tries to unpack array values sequentially (starting from the first index -- i.e. 0 ). However, starting from PHP 7.1, you can specify the specific key you're looking to unpack but we're not covering that since it's not within the scope of this article.

Get First Element of an Out-Of-Order or Non-Sequential Array

In PHP, there are a number of ways you could access the value of the first element of an out-of-order (or non-sequential) array. Please note that we'll be using the following array for all the examples that follow:

$names = [9 => 'john', 15 => 'jane', 22 => 'wayne'];

Using reset() :

The PHP reset() function not only resets the internal pointer of the array to the start of the array, but also returns the first array element, or false if the array is empty. This method has a simple syntax and support for older PHP versions:

// PHP 4+ echo reset($names); // output: "john"

Be careful when resetting the array pointer as each array only has one internal pointer and you may not always want to reset it to point to the start of the array.

Without Resetting the Original Array:

If you do not wish to reset the internal pointer of the array, you can work around it by creating a copy of the array simply by assigning it to a new variable before the reset() function is called, like so:

$namesCopy = $names; next($names); // move array pointer to 2nd element echo reset($namesCopy); // output: "john" echo current($names); // output: "jane"

As you can see from the results, we've obtained the first element of the array without affecting the original.

Using array_slice() :

// PHP 5.4+ echo array_slice($names, 0, 1)[0]; // output: "john"

Please note that by default array_slice() reorders and resets the numeric array indices. This can be changed however, by specifying the fourth parameter preserve_keys as true .

The advantage to using this approach is that it doesn't modify the original array. However, on the flip side there could potentially be an array offset problem when the input array is empty. To resolve that, since our array only has one element, we could use the following methods to return the first (also the only) element:

// PHP 4+ $namesCopy = array_slice($names, 0, 1); echo array_shift($namesCopy); // output: null if array is empty echo array_pop($namesCopy); // output: null if array is empty echo implode($namesCopy); // output: '' if array is empty // PHP 7+ echo $names_copy[0] ?? ''; // output: '' if array index is not set or its value is null
  • You must note though that using array_shift() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged.
  • Using both array_shift() and array_pop() resets the array pointer of the input array after use, but in our case that doesn't matter since we're using a copy of the original array, that too with only a single element.

Using array_values() :

// PHP 5.4+ echo array_values($names)[0]; // output: "john"

This method may only be useful if the array is known to not be empty.

In PHP 7+, we can use ?? (the null coalescing operator) to return the first index if it's set and not null, or return an empty string otherwise. For example:

// PHP 7+ echo array_values($names)[0] ?? '';

Using array_reverse() :

// PHP 4+ array_pop(array_reverse($names)); // output: "john"
  • By default array_reverse() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as true .
  • This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value.

Using foreach Loop:

We can simply make use of the foreach loop to go one round and immediately break (or return ) after we get the first value of the array. Consider the code below:

// PHP 4+ foreach ($names as $name) < echo $name; break; // break loop after first iteration >// or the shorter form foreach ($names as $name) break; // break loop after first iteration echo $name; // output: 'john'

Although it takes up a few lines of code, this would be the fastest way as it's using the language construct foreach rather than a function call (which is more expensive).

This could be written as a reusable function as well:

function array_first_value(array $arr) < foreach ($arr as $fv) < return $fv; >return null; // return null if array is empty >

Hope you found this post useful. It was published 28 Jul, 2016 (and was last revised 31 May, 2020 ). Please show your love and support by sharing this post.

Источник

Читайте также:  Python hacker guide pdf
Оцените статью