how to get only last value in a foreach? php - php

foreach ($data['data'] as $data) {
echo $data['title'][0];
//echo '<br />';
}
this will print out:
melon
apple
...
banana
pear
Now, how to jump all, only get the last value in a foreach? only need pear. Thanks.

If you only need the last value, then you don't need to loop. You can use end():
$lastItem = end($data['data']);
echo $lastItem['title'][0];
Note that this will set the internal array pointer to the last element. It might be necessary that you call reset($data) afterwards.

End has already been suggested (which I can recommend actually), however if you want to do it with foreach, you could do:
foreach ($data['data'] as $data) {
}
echo $data['title'][0];
//echo '<br />';
but this is really superfluous. You iterate over the array then only to store the last element into $data. So if there are no elements in 'data' at all this will fail (as with end, but end will return a false if the array is empty).
So go for:
$data=end($data['data']);

Related

How to put an Array Value to echo individually

I want to echo the array on a different location but I cannot make it to work.
i can echo the array if I do these
foreach($domain as $value) {
echo $value;
}
bot cannot echo it individually
foreach($domain as $value) {
$domainame[] = $value;
}
echo '<p> your first domain' .$domainname[0];
echo '<p> your last domain' .$domainname[5];
There are many ways to do this:
var_export($array);
var_dump($array);
print_r($array);
For each of the above it's useful to first ( when outputting to html )
echo "<pre>";
A pre tag to preserve the white space. Each one of these have some uniqueness to them. While I cant cover them all.
var_export - outputs valid PHP comparable text, so you can paste an array right into your code after outputting it with this. It has a second argument $string = var_export($array,true) that will return it as a string
var_dump - tells you the type of variable, such as int, array etc..
print_r - is more "human" readable.
If you want to get really wild you can use, array_map instead of a loop:
array_map(function($item){
echo $item;
}, $array);
At first one would think you could simply do
array_map('echo', $array);
But, alas echo is not a real function, it's a language construct, so you have to wrap it in a closure. Compare this to var_dump
array_map('var_dump', $array )
Works just fine.
And last but not least you could always do
echo json_encode($array);
But that probably won't be to readable.
I am sure there are some I am forgetting.
UPDATE
I thought you just wanted to generally output it. Anyway, you can use array_map
array_map(function($item){
echo "<p> your first domain{$domainame[0]}</p>"; //dont forget the typo
}, $array);
I think #Alive to Die, got it with the typo. But, if you output it using any of the above you would see it was empty.
One thing I should mention, as you should have gotten a warning for this, when developing you should have error reporting turned on ether globally in the php.ini or at least in the file your working on
<?php
error_reporting(-1); //error level E_ALL
ini_set('display_errors', 1); //output errors
you can simply write:
echo '<p> your first domain' .$domain[0];
echo '<p> your last domain' .$domain[5];
no point of looping at all!
you have to do like this
$i = 0;
foreach($domain as $value){
$domainame[$i] = $value;
$i++;
}
and now you can do this
echo '<p> your first domain' .$domainname[0];

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

Returning string value in php array

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'
try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array
Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.
Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

Strange foreach loop after modifying array

As I wrote some code, PHP confused me a little as I didn't expected the result of the following code:
$data = array(array('test' => 'one'), array('test' => 'two'));
foreach($data as &$entry) {
$entry['test'] .= '+';
}
foreach($data as $entry) {
echo $entry['test']."\n";
}
I think it should output
one+
two+
However the result is: http://ideone.com/e5tCsi
one+
one+
Can anyone explain to me why?
This is expected behaviour, see also https://bugs.php.net/bug.php?id=29992.
The reference is maintained when using the second foreach, so when using the second foreach the value of $entry, which points still to $data[1], is overwritten with the first value.
P.s. (thanks to #billyonecan for saying it): you need to unset($entry) first, so that your reference is destroyed.
This is mentioned specifically in the documentation for foreach. You should unset the loop variable when it gets elements of the array by reference.
Warning
Reference of a $value and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset().

How to get specific instance in PHP array?

I am trying to get the specific value of file extension in this array. All I can do so far is .
I am wanting the fileextention ".jpg"
All I know how to do is echo the values like so using foreach;
file_nameBob7213.jpg file_typeimage/jpeg
file_pathC:/xampp/htdocs/midas/records/
full_pathC:/xampp/htdocs/midas/records/Bob7213.jpg raw_nameBob7213
orig_nameBob72.jpg client_nameafasfafs.jpg **file_ext.jpg** file_size44.96
is_image1 image_width716 image_height474 image_typejpeg
image_size_strwidth="716" height="474"
I am only interested in retrieving the file_ext from this array. How do I select that exact thing?
foreach ($file['upload_data'] as $item => $value)
{
echo $item; echo $value; echo "<br/>";
}
How do I do this? , thanks!
$file['upload_data']['file_ext']
It's just an array within an array, so specify 2 array keys
Incidentally, if you want to see the contents of an array, a quick way of doing it is to use var_export:
var_export($file); # echoes the entire array
You don't need to write a foreach loop every time
$file['upload_data']['file_ext'] contains '.jpg'.

Categories