Count values with the same value inside loop - php

I try count elements inside loop, with the same value, as i put in my title, now i show my little script fot try to do this :
<?php
$values="1,2,3~4,5,2~7,2,9";
$expt=explode("~",$values);
foreach ($expt as $expts)
{
$expunit=explode(",",$expts);
$bb="no";
foreach($expunit as $expunits)
{
//// $expunit[1] it´s the second value in each explode
if ($expunits==="".$expunit[1]."")
{
$bb="yes";
}
if ($bb=="yes")
{
print "$expunits --- $expunit[1] ok, value it´s the same<br>";
}
else
{
print " $expunits bad, value it´s not the same<br>";
}
}
}
?>
THE SCRIPT MUST SHOW DATA IN THIS WAY :
$values="1,2,3~4,5,2~7,2,9";
**FIRST ELEMENTS WITH THE SAME SECOND ELEMENT, IN VALUES COMMON VALUE IT´S NUMBER 2, BECAUSE IT´S IN SECOND POSITION **
FIRST :
1,2,3
7,2,9
LAST THE OTHERS
4,5,2
I try verificate the second position, between delimeters, because it´s value i want verificate for count inside loop, while explode string, actually give bad values, i think it´s bad because don´t get real or right values, i don´t know if it´s possible do it or with other script or change something in this
Thank´s Regards

EDIT - this is a bit closer to what you are looking for (sorry it is not perfect as I do not have time to work on it fully):
$values="1,2,3~4,5,2~7,2,9";
$values=explode("~",$values);
foreach($values as $key => $expt) {
$expit=explode(",",$expt);
$search_value = $expit[1];
$matched=array();
foreach($values as $key2 => $expt2) {
if($key !== $key2) {
$expit2=explode(",",$expt2);
if($expit[1]==$expit2[1]) {
$matched[] = $expit[1];
}
}
}
}
array_unique($matched);
foreach($matched as $match) {
$counter = 0;
$no_matches = array();
echo "<br />Matching on digit ".$match;
foreach($values as $key3 => $expt3) {
$expit3=explode(",",$expt3);
if($match == $expit3[1]) {
echo "<br />".$expt3;
$counter++;
} else {
$no_matches[] = $expt3;
}
}
echo "<br />Total number of matches - ".$counter;
echo "<br />Not matching on digit ".$match;
foreach($no_matches as $no_match) {
echo "<br />".$no_match;
}
}
Outputs:
Matching on digit 2
1,2,3
7,2,9
Total number of matches - 2
Not matching on digit 2
4,5,2

Related

Find Next to Last Element in PHP Foreach

I need to write a script that returns the next-to-last element in a foreach loop. Something like the below concept. How would I go about doing so?
foreach($row as $r) {
if (element index is last - 1) {
echo "The next-to-last element is" . $r;
}
}
This should work for you:
Just get the keys of your array into a variable and then check if the current key of the iteration is equal to the penultimate key.
$keys = array_keys($row);
$penultimatekey = count($row)-2 >= 0 ? count($row)-2 : 0;
foreach($row as $k => $r) {
if ($k == $keys[$penultimatekey]) {
echo "The next-to-last element is" . $r;
}
}
Move the pointer to the end, then rewind it by one spot. No extra loops or counting the array.
end($row);
prev($row);
echo "The next-to-last element is: " . current($row);

How to only show the first line of print print_r?

How do you echo only the first line of print print_r?
More info:
I have this PHP code:
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
foreach(end($matches) as $key=> $value){
print print_r($value, 1).'<br>';
}
That results in:
12567682
12764252
12493678
14739908
(or other numbers depending on user input)
I tried:
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
foreach(end($matches) as $key=> $value){
$id = print_r($value, 1).'<br>';
}
echo $id
But it results in 1 random number from the list. In other words, the result only shows when using print like ' print print_r($value, 1).'<br>';'. The problem is that I only want the first, inorder, result to be shown. As if:
$firstlineofnumbers = '12567682';
echo $firstlineofnumbers;
Hope this makes sense. Thanks (:
If I understood what you're trying to do, just adding a break; statement after outputting the first value should be enough:
foreach(end($matches) as $key=> $value){
print print_r($value, true).'<br>'; // print_r() expects true, not 1
break;
}
If the keys in $matches are always numeric keys, this code should be enough:
echo $matches[0];
Otherwise, try this code:
$keys = array_keys($matches);
echo $matches[array_shift($keys)];
$keys will contain all keys of $matches.
array_shift will return the first value of $keys (the first key).
So the last line will display the corresponding value.
There is no need to loop through the entire array if you only need to display the first element.
preg_match_all('/MbrDtlMain.php\?([^ ]+)>/i', $string, $matches);
$i=0;
foreach(end($matches) as $key=> $value){
$i++;
if ($i == 1) {
echo $value."<br />";
}
}
This starts with the variable $i which increases by 1 for each match. If $i == 1, then it will echo the $value.

php foreach as key, every two number as a group

<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
if($key % 2 != 0){
echo $element.'<br />';
}
echo '<hr />';
}
?>
php foreach as key, how to make every two number as a group?
I want to output:
1,2
_____
3,4
_____
5,6
_____
7,8
_____
9,10
_____
11
Have a look at the array_chunk() function.
In your case you'd use it like this:
foreach(array_chunk($data, 2) as $values) {
echo implode(',', $values)."\n";
}
During the last iteration $values will have only one element so if you plan to access the elements directly using their index remember to use count() to check the array's element count.
Your foreach() is fine but you want to print every element, not just every even one. You also don't want the horizontal rule every time either, just every even. Thus:
<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
echo $element;
if($key % 2 != 0){
echo "<br/><hr />";
}
else {
echo ",";
}
}
?>

Foreach loop, but for first key do something else

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");

PHP display problem?

For some reason when an array has for example, four values it will display all four values four times I just want the values to be displayed one time.
How can I fix this problem? Note the first echo works perfectly.
Here is the code.
if (count($array) == 1){
echo $array[$x] . " one value has been entered";
} else {
echo implode(", ", $array) ." you entered more then one value;
}
Because $x obviously isn't the index of the first element of the array. Use the correct index. Or if you don't know what it is, just use reset():
if (count($array) == 1) {
echo reset($array) . ' one value has been entered';
} else {
echo implode(', ', $array) . ' you entered more than one value';
}
It might be helpful to dump the array to see what it actually contains:
print_r($array);
$x is not set in your code or just meaningless. If you have just one array item you can print it with the simple echo $array[0];

Categories