Hello here i am with freaky problem,i wants the first data and last data from for-each loop. for that i have seen this answer. this would be really helpful but here my condition is really a little bit complex.
I have loop as following
<?php
$count = 0;
$length = count($myDataArray);
foreach ($myDataArray as $value) {
if($count >= 7)
{
//Some Data to Print
//this is first data for me
<tr >
<td><?=$myfinaldate?></td>
<td><?=$stockdata[1]?></td>
<td><?=$stockdata[2]?></td>
<td><?=$stockdata[3]?></td>
<td <?php if($count == 8)echo "style='background-color:#47ff77;'"; ?>><?=$stockdata[4]?></td>
<td><?=$stockdata[5]?></td>
<td><?php echo $mydate; ?></td>
</tr>
<?php
}
$count++;
}
Now How can i Get First And Last Data from loop ?
I imagine you could use your length attribute.
As you have the total of your array, just check
myDataArray[0] and myDataArray[$length-1] ?
To fetch first and last value of the array use the below function :
$array = $myDataArray;
$array_values = array_values($myDataArray);
// get the first value in the array
print $array_values[0]; // prints 'first item'
// get the last value in the array
print $array_values[count($array_values) - 1]; // prints 'last item'
You can use array_values to remove the keys of an array and replace them with indices. If you do this, you can access the specified fields directly. Like this you can check for your requirements on the array without looping over it, as shown in the if-conditions below:
$length = count($myDataArray);
$dataArrayValues = array_values($myDataArray);
$wantedFields = [];
if ($length >= 8) {
$wantedFields[] = $dataArrayValues[7];
if ($length > 8) {
$wantedFields[] = end($dataArrayValues);
}
}
Due to the conditions you will not print the 8th field twice in case it is the last field as well.
foreach ($wantedFields as $value) {
<tr>
... //Your previous code
</tr>
}
Related
I am facing the problem is that I want to display all image by using array and loop,it is not showing all image ,it does show only one image.Here is my code
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths = array($img11[$i]);
}
}
here is in the database to extract out all image
the out put is showing only one image by using this code
<? echo $im_mouths[0].'11111'.'<br>';?>
<? echo $im_mouths[1].'222222'.'<br>';?>
<? echo $im_mouths[2].'333333'.'<br>';?>
I am not sure I'm doing correctly or not ,help me out this problem.
Thanks :)
It's only showing one image because you're re-writing $im_mouths each time you loop. You should change your loop to do the following:
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
We initialize $im_mouths as an array, then add each element to the array as an element: $im_mouths[] = ....
You need to simplify your code a bit.
Assuming you have a outer loop for retrieving data from database:
$im_mouths = array();
while ($objResult = $res->fetch()) {
if($objResult['Image_Type'] == '01') {
$im_mouths[] = $objResult['Image_Name'];
}
}
Now you have $im_mouths array of elements of image names, as many as you have in database. So as you see you don't need unnecessary inner for loop
Finally to see what you have in your $im_mouths array, you can print_r it:
print_r($im_mouths);
In your example, the variable $im_mouths should contain only the last image ( that is, 20140923jaobangsaen01.png ). Because you are using simple variable to store the image, so that the variable may contain last image while the program flow comes out from the for loop. So that the output of your example is correct. If you want to show each images means, you should use array variable to store all the images and display back to the required place. Rearrange the code like following,
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
Hope it will work fine for you.
Use can use foreach to display the images instead of using echo for each image.
$num = 1111; //if required
foreach ( $im_mouths as $value ) {
echo $value.$num;
$num += 1111;
}
How do I delete the whole line from an array? When the delete-button is pressed it should delete the whole line.
my array looks like that:
$liste[0][0] = email-user1
$liste[0][1]= password-user1
$liste[1][0] = email-user2
$liste[1][1]= password-user2
So if I delete the user one, the user2 should just take the place from user1(which should just disappear).
if (isset($_GET['delete'])){
$id=key($_GET['delete']);
for ($i = 0; $i < count($liste); $i++){
if ("$i"=="$id"){
unset($liste[$id][0]);
unset($liste[$id][1]);
unset($liste[$id][2]);
}
else{
}
}
update
I'm using array_splice($liste, $id, 1); now but everytime I try to save it to the file I get an error: implode(): Invalid arguments passed. For saving it to the file, I use the following function:
function saveDataToFile($fileName, $liste){
$file=fopen($fileName,"w");
for ($i = 0; $i < count($liste); $i++) {
$zArray=$liste[$i];
$zeile=implode("|", $zArray);
if(strlen($zeile) > 0){
$zeile=$zeile."\r\n";
fwrite($file, $zeile);
}
}
fclose($datei);
}
Try the below code:
$liste[0][0] = "email-user1";
$liste[0][1]= "password-user1";
$liste[1][0] = "email-user2";
$liste[1][1]= "password-user2";
$liste[2][0] = "email-user3";
$liste[2][1]= "password-user3";
unset($liste[1]); // say you want to delete this row
$new_arr = $liste;
unset($liste);
$i=0;
foreach($new_arr as $value){
$liste[$i] = $value;
$i++;
}
You can use array_splice() method:
array_splice($liste, $id, 1);
$liste[0][0], $liste[0][1] and $liste[0][2] are in real nothing else than a value array(value, value, value) (the inner array) which is assigned to $liste[0] (the outer array)
unsetting this (outer) array value $liste[0] is enough:
unset($liste[$id]);
If you care about the keys of this array (I see you loop from 0..n), you need to reindex your array using:
$liste = array_values($liste);
This will make your array behaving more like arrays normally do in other programming languages
Good practice is to use foreach instead of for. In this case you don't need to reindex:
for ($liste as $key=>$value){
if ("$key"=="$id"){
unset($liste[$key]);
}
But anyway you don't have to loop through an array just for finding a key. It's enough doing this:
if (isset($liste[$id])) { /* optional: check if the key exists */ }
unset($liste[$id]);
I'm pretty new to PHP and programming so I'm having troubles with this thing.
The purpose of the whole situation is to read a column from tab delimited file (already did that), get all different items in it, count them individually and put them in table with Column1[item value - label], Column2[count].
I have the whole column in 1 dimension array. Now, I want to list all the items there and their counts beside. The problem is, I could have more than 10 different items, even more, so I can't do it manually (name 10 variables and count each) like this:
$arr = array("complete","fail","complete","exit","fail","fail","complete");
function isComplete($value){
return ($value == "complete") ? true : false;
}
$complete = array_filter($array, 'isComplete');
<tr>
<td>Complete</td>
<td><?php echo count($complete)?></td>
</tr>
-- > Complete = 3
I want to avoid manually creating every function for each value because values can differ from file to file.
The number of items in $array can go up to 20+k so I need all automated. Can someone help me with this?
How about going through the array and placing the counts in another array? ($arrCount)
$arr = array("complete","fail","complete","exit","fail","fail","complete");
$arrCount = Array();
foreach($arr as $value){
$arrCount[$value] = array_key_exists($value,$arrCount) ? $arrCount[$value]+1 : 1;
//If this key exists, add 1 to it, else make it equal to 1
}
This would create an array with the keys being the various labels and the value equally to the label total.
print_r output:
Array ( [complete] => 3 [fail] => 3 [exit] => 1 )
Psuedo code:
$arr = array("complete","fail","complete","exit","fail","fail","complete");
$counts = array();
foreach($arr => $key as $value)
{
if(array_key_exists($value, $counts))
{
$counts[$value]++;
}else{
$counts[$value] = 1;
}
}
foreach($counts => $key as $value)
{
echo '<tr>
<td>' . $key . '</td>
<td>' . $value . '</td>
</tr>';
}
We are making arrays of the elements in the list. If the item exists, increase otherwise create with value 1. Than loop another time to show to the user the total count of each item.
Maybe I'm missing the point, but what is the problem with a normal loop?
For example:
function countByValue($array, $value){
$count = 0;
foreach($array as $val){
if ($val == $value){
$count++;
}
}
return $count;
}
And call it with
$complete = countByValue($arr, 'complete');
If you want to count them all at once go with F4r-20 answer.
Thanks in advance for looking.
I am trying to build some HTML using a foreach loop with a few layers of arrays.
Groups of data and groups of titles for that data are stored in sets of arrays.
In turn, those arrays of data are stored in an array ($titlegroups and datagroups).
The aim being to set up a nested loop, where each group of data and titles populate the relevant fields in some html.
Here is a full set of code (structure) of my attempt.
$a=1;
$b=2;
$c=3;
$d=4;
$titlesA=array('string1','string2');
$titlesB=array('string3','string4');
$dataA=array($a,$b);
$dataB=array($c,$d);
$titlegroups=array($titlesA,$titlesB);
$datagroups=array($dataA,$dataB);
$groups=array(array_combine($titlegroups, $datagroups));
$j=0;
foreach($groups as $titlesX => $dataX)
{
$j++;
echo'<div class="something">';
$i=0;
foreach(array_combine($titlesX, $dataX) as $title => $var)
{
$i++;
echo '
<li>'.$title.'</li><input name="'.$j.'x'.$i.'" value="'.$var.'" />
';
}
echo '</div>';
}
Checking it in ideone I get the error:
Warning: array_combine() expects parameter 1 to be array, integer
given in /home/0zw0mb/prog.php on line 26
Line 26 is:
foreach(array_combine($titlesX, $dataX) as $title => $var)
but $titlesX and $dataX should both be arrays?
If anyone can set me straight I'd appreciate it. Thanks.
You can't have arrays as keys, they are converted to strings. You logic required some changes and an additional sentinel variable ($idx), to tell when the code crosses one group to another.
array_merge was necessary due to the key requirements of arrays.
Check the below code:
$a=1;
$b=2;
$c=3;
$d=4;
$titlesA=array('string1','string2');
$titlesB=array('string3','string4');
$dataA=array($a,$b);
$dataB=array($c,$d);
$titlegroups=array_merge($titlesA,$titlesB);
$datagroups=array_merge($dataA,$dataB);
$items=array_combine($titlegroups, $datagroups);
$indexes = array(count($dataA), count($dataB));
$i = 0;
$j = 0;
$idx = $indexes[$j];
echo '<div class="something">';
foreach($items as $title => $var)
{
echo '
<li>'.$title.'</li><input name="'.$j.'x'.($i++).'" value="'.$var.'" />
';
$idx--;
if ($idx == 0) {
/* End of a group */
echo '</div>';
$idx = $indexes[++$j];
/* If there is another group, create new container */
if ($idx != null) {
echo '<div class="something">';
}
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Search for PHP array element containing string
I've created a mysql query that pulls through several products, all with the following information:
Product ID
Product Name
Product Price
and
Product Category
Further down the page, I've looped through these with a foreach and a few 'ifs' so it only displays those products where the name contains 'x' in one div and displays those products where the name contains 'y' in another div.
I'm struggling to count how many products are going to be in each div before I do the loop.
So essentially, what I'm asking is:
How do you count all elements in an array that satisfy a certain condition?
Added Code which shows the loop:
<div id="a">
<?php
$i = 1;
foreach ($products AS $product) {
if (strpos($product->name,'X') !== false) {
=$product->name
}
$i++;
} ?>
</div>
<div id="b">
$i = 1;
foreach ($products AS $product) {
if (strpos($product->name,'Y') !== false) {
=$product->name
}
$i++;
} ?>
</div>
I'd like to know how many of these are going to be in here before I actually do the loop.
Well, without seeing the code, so generally speaking, if you're going to split them anyway, you might as well do that up-front?
<?php
// getting all the results.
$products = $db->query('SELECT name FROM foo')->fetchAll();
$div1 = array_filter($products, function($product) {
// condition which makes a result belong to div1.
return substr('X', $product->name) !== false;
});
$div2 = array_filter($products, function($product) {
// condition which makes a result belong to div2.
return substr('Y', $product->name) !== false;
});
printf("%d elements in div1", count($div1));
printf("%d elements in div2", count($div2));
// then print the divs. No need for ifs here, because results are already filtered.
echo '<div id="a">' . PHP_EOL;
foreach( $div1 as $product ) {
echo $product->name;
}
echo '</div>';
echo '<div id="b">' . PHP_EOL;
foreach( $div2 as $product ) {
echo $product->name;
}
echo '</div>';
That being said: you should take notice of the comment which says "This is normally faster in SQL", because it is the more sane approach if you want to filter the values.
EDIT: Changed the name of the variables to adapt the variable names in the example code.
Use an array-filter: http://www.php.net/manual/en/function.array-filter.php
array array_filter ( array $input [, callable $callback = "" ] )
Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
<?php
function odd($var)
{
// returns whether the input integer is odd
return($var & 1);
}
function even($var)
{
// returns whether the input integer is even
return(!($var & 1));
}
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>
But be aware, this is a loop though, and your the SQL query will be faster.