php foreach Loop try not to copy a array [duplicate] - php

This question already has answers here:
How to remove duplicate values from an array in PHP
(27 answers)
Closed 9 years ago.
Is there any way of not copying the specific array in the foreach loop?
Here's the code
<?php
$letters = array("A","B","B","C");
foreach ($letters as $char){
if ($char == "B") {
continue;
}
echo $char;
}
?>
I want my output to be only ABC not AC

You could strip non-unique elements first:
foreach(array_unique($letters) AS $char)

To copy array use
$a = array("A","B","B","C");
$b = array_unique($a); // $b will be a different array with unique values
There is no need to use foreach. In PHP by default variables are not assigned by reference but by the value unless you use & operator.
The other way is to use array_merge()
$a = array("A","B","B","C");
$b = array();
$b = array_merge(array_unique($a), $b);
In both cases the result will be A B C

Try like
<?php
$letters = array("A","B","B","C");
$letters = array_unique($letters);
foreach ($letters as $char){
echo $char;
}
?>

Related

Why does For work, but ForEach does not in PHP? [duplicate]

This question already has answers here:
Why can't I update data in an array with foreach loop? [duplicate]
(3 answers)
Closed 1 year ago.
We have an array of strings of numbers
$a = ["1", "2", "3"];
foreach loop doesn't change the type, result: [0]=>string(1) "1"
foreach ($a as $v) $v = (int) $v;
for loop makes ints from strings, result: [0]=>int(1)
for ($i = 0; $i < count($a); $i++) $a[$i] = (int) $a[$i];
Please, explain why is that?
The same reason that
$v = $a[0];
$v = int($v);
doesn't change $a. $v is a copy of the array element, not a reference to it.
You can make it work using a reference variable
foreach ($a as &$v) {
$v = (int)$v;
}

Create groups of values from array values [duplicate]

This question already has answers here:
Finding the subsets of an array in PHP
(5 answers)
Closed 7 years ago.
I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:
If i have this code:
array('ec','mp','ba');
I would like to be able to output something like this:
'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'
Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing
You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:
$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
foreach ($arr as $s2) {
if ($s1 < $s2) {
$result[] = array($s1, $s2);
}
}
}
You can do it as follows:
$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');
$newArr = array();
foreach($arr as $key=>$val) {
if($key % 2 == 0) {
$newArr[] = $val;
} else {
$newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
}
}
print_r($newArr);
And the result is:
Array
(
[0] => ec,mp
[1] => ba,ds
[2] => sd,ad
)
Have you looked at the function implode
<?php
$array = array('ec','mp','ba');
$comma_separated = implode(",", $array);
echo $comma_separated; // ec,mp,ba
?>
You could use this as a base for your program and what you are trying to achieve.

PHP array get next key/value in foreach() [duplicate]

This question already has answers here:
Get next element in foreach loop
(11 answers)
Closed 9 years ago.
I am looking for a way to get the next and next+1 key/value pair in a foreach(). For example:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
foreach($a AS $k => $v){
if($nextval == $v && $nextnextval == $v){
//staying put for next two legs
}
}
You can't access that way the next and next-next values.
But you can do something similar:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
$keys = array_keys($a);
foreach(array_keys($keys) AS $k ){
$this_value = $a[$keys[$k]];
$nextval = $a[$keys[$k+1]];
$nextnextval = $a[$keys[$k+2]];
if($nextval == $this_value && $nextnextval == $this_value){
//staying put for next two legs
}
}
I've found the solution with complexity O(n) and does not require seeking through array back and forward:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
// initiate the iterator for "next_val":
$nextIterator = new ArrayIterator($a);
$nextIterator->rewind();
$nextIterator->next(); // put the initial pointer to 2nd position
// initiaite another iterator for "next_next_val":
$nextNextIterator = new ArrayIterator($a);
$nextNextIterator->rewind();
$nextNextIterator->next();
$nextNextIterator->next(); // put the initial pointer to 3rd position
foreach($a AS $k => $v){
$next_val = $nextIterator->current();
$next_next_val = $nextNextIterator->current();
echo "Current: $v; next: $next_val; next_next: $next_next_val" . PHP_EOL;
$nextIterator->next();
$nextNextIterator->next();
}
Just remember to test for valid() if you plan to relay on the $next_val and $next_next_val.
Here's one way to do it:
while($current = current($a)) {
$next = next($a);
$nextnext = next($a);
// Comparison logic here
prev($a); // Because we moved the pointer ahead twice, lets back it up once
}
Example: http://3v4l.org/IGCXW
Note that the loop written this way will never examine the last element in your original array. That could be fixed, although with your current logic it doesn't seem to matter since there are no "more" elements to compare the last one to.
Have a look at CachingIterator, as described in this answer:
Peek ahead when iterating an array in PHP
Or use array_keys() is in another answer posted for the same question, e.g.
$keys = array_keys($array);
for ($i = 0; $i < count($keys); $i++) {
$cur = $array[$keys[$i]];
$next = $array[$keys[$i+1]];
}
You can't simply "stay put" in a loop. I suspect you're looking to do something a lot easier than write custom iterators. If you simply want to ignore entries with duplicate keys, then track the last key and compare it to the current one.
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
// Prints LA NY FL
$last_v = null;
foreach ( $a as $k => $v ){
if ( $last_v == $v ) {
/**
* Duplicate value, so skip it
*/
continue;
}
echo $v.' ';
$last_v = $v;
}
Funny, I'm programming PHP for a decade (with years pause), but I needed one-by-one walk functions just a week ago.
Here you are: next, prev, reset etc. See "see also" section. Also, check array_keys()

How can I iterate through two arrays at the same time without re-iterating through the parent loop? [duplicate]

This question already has answers here:
php looping through multiple arrays [duplicate]
(8 answers)
Closed 9 years ago.
How can I iterate through two arrays at the same time that have equal sizes ?
for example , first array $a = array( 1,2,3,4,5);
second array $b = array(1,2,3,4,5);
The result that I would like through iterating through both is having the looping process going through the same values to produce a result like
1-1
2-2
3-3
4-4
5-5
I tried to do it this way below but it didn't work , it keeps going through the first loop again
foreach($a as $content) {
foreach($b as $contentb){
echo $a."-".$b."<br />";
}
}
Not the most efficient, but a demonstration of SPL's multipleIterator
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$newArray = array();
foreach ( $mi as $value ) {
list($value1, $value2) = $value;
echo $value1 , '-' , $value2 , PHP_EOL;
}
Use a normal for loop instead of a foreach, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
If they're the same size, just do this:
foreach($a as $key => $content){
$contentb = $b[$key];
echo($content."-".$contentb."<br />");
}

PHP - how many times [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to find the repeating elements in an array?
If I have this array : array("hey", "test", "hey");
And I want to count how many times I have the word "hey", how can I do that?
Wouldn't it be great if there were a function like array_count_values?
</sarcasm>
Some example code of usage:
$arr = array(...);
$valCounts = array_count_values( $arr );
echo $valCounts['hey'];
I highly recommend browsing php.net and, in-particular, learning the array functions.
$count = 0;
foreach($array as $item) {
if($item == 'hey') {
$count++;
}
}
print $count;
The command is array_count_values. Check
http://www.php.net/manual/en/function.array-count-values.php
You just need to loop over the array.
$x = 0;
foreach (array("hey","test","hey") as $value) {
if ($value === "hey") $x++;
}
For a less efficient, but shorter, solution, you could use array_count_value.
$counts = array_count_values(array("hey","test","hey"));
$x = $counts["hey"];

Categories