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];
Related
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
I have a while loop that loops through line of text
while ($line_of_text = fgetcsv($file_processing, 4096)) {
In this while loop I assign variables to different parts of the array
IF($i > 0)
{
echo "</br>";
$account_type_id = $line_of_text[0];
echo "Account Type ID: " . $account_type_id. "<br>";
$account_number = $line_of_text[1];
echo "account_number = " . $account_number . "<br>";
This while loop loops through many lines. I am trying to find a way to say that
IF $account_type_id == 99 then add $account_number to an array. Then outside of the while loop print out the whole array of $account_numbers where $account_type_id == 99.
I have tried using print_r but it will only display the last array...
To add the element to an array, you can use array_push.
First you need to create the array (before the while loop):
$my_array = array();
Then, in the while loop, do this:
if ($account_type_id == 99) {
array_push($my_array, $account_number);
}
Then to display the array, either use print_ror var_dump. To make the array easier to read, you can also do this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Rocket H had the answer in the comment he posted
inside of your loop
if($account_type_id == 99){
$account_numbers[] = $account_number;
}
After loop
print_r($account_numbers);
I am trying to learn php, and I am playing around with while loops. I was wondering how to print out a specific number in an array in php. Fx:
$a = [1,3,5,7,9,11,13];
$s = 3;
while($a == 3) {
echo $s.' is in the row';
$a++;
}
In this example I would like to run through the $a and see if 3 exist there. If it does it has to echo '3 is in the row' I tried to make a while loop, but it is not correct. Can anyone see what I am doing wrong? Just to say it, I think it is very wrong, but I don't know how to solve it, if I have to use the while loop?
Best Regards
Mads
Your while condition reads: "While the value of $a equals 3", but $a is an array, so its value can't ever be 3. The loop will never be executed. In PHP, we would write:
if (in_array($s, $a))
echo $s, ' was found in the array';
Or, if you insist on writing loops:
foreach ($a as $key => $value)
{
if ($value == $s)
{
echo $s, ' was found at offset ', $key;
break;//end terminate loop
}
}
Of course, you could also write:
for ($i=0, $j=count($a);$i<$j;++$j)
{
if ($a[$i] == $s)
{//you could move this condition to the loop itself, even
echo $s, ' found in array at offset ', $i;
break;
}
}
You can, if you want use a while loop, too, but that wouldn't be the best choice for your particular case. Just read through the manual on php.net. There are many, many array_* functions available, and there are many ways to iterate over your data.
Another worry is your using the array name as a sort-of C-style pointer: $a++; in C, an pointer can be incremented to set it to point to the next value in an array (if the new memory address is valid, and the pointer is valid, and all of the other things you have to worry about in C). PHP does not work this way. An array isn't really an array: it's a hash map. incrementing an array, therefore, is pointless and most likely to be a bug. The for loop is the closest you can get to traversing an array using the ++ operator.
You're looking for in_array. This checks if a value exists in an array, in the form of:
in_array ( mixed $needle , array $haystack )
So, in your case, you'd want to do:
$a = [1,3,5,7,9,11,13];
$s = 3;
if (in_array($s, $a)) {
echo $s.' is in the row';
}
foreach($a as $b) {
if($b == 3)
echo $b.' is in the row';
}
Modify slightly your code changing while condition:
$a = array(1,3,5,7,9,11,13);
$s = 3;
$counter = 0;
while($counter < count($a)) {
if ( $a[$counter] == $s )
echo $s.' is in the row';
$counter++;
}
Added counter to iterate through while loop until end of array.
count() method returns number of items in array.
This solution prints all occurences of your number.
To have better code, change names of variables:
$numbers = array(1,3,5,7,9,11,13);
$target = 3;
$counter = 0;
while($counter < count($numbers)) {
if ( $numbers[$counter] == $target )
echo $target.' is in the row';
$counter++;
}
There are two ways to do it,
First, you can loop through all items in the array using a foreach() loop.
That way, you can go through them all and if you have multiple conditions, it makes your code a bit more readable.
And example of that loop is like this:
foreach($array as $array_item) {
if($array_item === 3) {
echo "3 is in the array";
}
}
The alternative is to use a built in function to find if something is in the array. THis is probably much faster, though I haven't benchmarked the difference.
if(in_array(3, $array)) {
echo "3 is in the array";
}
you can use
array_search ,in_array , and forearch or for loops to itertate through the array.
For learning purposes
$a = [1,3,5,7,9,11,13];
$s = 3;
for($i=0;$i<count($a);$i++)
{
if($a[$i]==$s){
echo $s.' is in the row';
}
}
of course in real life
if (in_array(3, $a)) {
// Do something
}
would be better;
<?php
$a = [1,3,5,7,9,11,13];
$s = 3;
for($a=0;$a < 20; $a++)
{
while($a == 3) {
echo $s.' is in the row';
//$a++;
}
}
?>
Is there a way to easily check if the values of multiple variables are equal? For example, in the code below I have 10 values, and it's cumbersome to use the equal sign to check if they're all equal.
<?
foreach($this->layout as $l):
$long1=$l['long1_campaignid'];
$long2=$l['long2_campaignid'];
$long3=$l['long3_campaignid'];
$long4=$l['long4_campaignid'];
$long5=$l['long5_campaignid'];
$long6=$l['long6_campaignid'];
$long7=$l['long7_campaignid'];
$long8=$l['long8_campaignid'];
$long9=$l['long9_campaignid'];
$long10=$l['long10_campaignid'];
endforeach;
?>
for example
if $long1=3,$long2=7,$long3=3,$long4=7,$long5=3 etc,
i need to retrieve $long1=$long3=$long5 and $long2=$long4
I think this is what you're looking for:
<?
foreach($this->layout as $l):
$m = array_unique($l);
if (count($m) === 1) {
echo 'All of the values are the same<br>';
}
endforeach;
?>
I assuming that you are looking to see if all of the values in the array are the same. So to do this I call array_unique() to remove duplicates from the array. If all of the values of the array are the same this will leave us with an array of one element. So I check for this and if it is true then all of the values are the same.
The example showed at the question is about "grouping" not directly about "find equal variables".
I think this simple "grouping without change the order" algorithm is the answer... Other algorithms using sort() are also easy to implement with PHP.
<?
foreach($this->layout as $l) {
$m = array();
foreach($1 as $k=>$v) // keys 'longX' and values
if (array_key_exists($v,$m)) $m[$v][] = $k;
else $m[$v] = array($k);
foreach ($m as $val=>$keys)
if (count($keys)>1) echo "<br/> have SAME values: ".join(',',$keys)
}
?>
About "find equal variables"
Another (simple) code, see Example #2 at PHP man of array_unique.
<?
$m = array_unique($this->layout);
$n = count($m);
if ($n == 1)
echo 'All of the values are the exactly the same';
elseif ($n>0)
echo 'Different values';
else
echo 'No values';
?>
The "equal criteria" perhaps need some filtering at strings, to normalize spaces, lower/upper cases, etc. Only the use of this "flexible equal" justify a loop. Example:
<?
$m = array();
foreach($this->layout as $l)
$m[trim(strtolower($1))]=1;
$n = count(array_keys($m));
if ($n == 1)
echo 'All of the values are the exactly the same';
elseif ($n>0)
echo 'Different values';
else
echo 'No values';
?>
If #John Conde's answer is not what you are looking for and you want to check for one or more of the same values in the collection, you could sort the array and then loop through it, keeping the last value and comparing it to the current value.
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'], ", ");