PHP, "Foreach" using 3 arrays [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
foreach with three variables add
If I have 3 arrays of the same size, is it possible to use the costruct foreach() to cycle in the same time the 3 arrays?
ex.
$name contains names
$surname contains surnames
$address contains addresses.
Can foreach take elements [1], [2], [.....] in the same time, to print
$name[1], $surname[1], $address[1];
$name[2], $surname[2], $address[2];
and so on?

SPL's multipleIterator is designed for precisely this purpose
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($array1));
$mi->attachIterator(new ArrayIterator($array2));
$mi->attachIterator(new ArrayIterator($array3));
foreach ( $mi as $value ) {
list($name, $surname, $address) = $value;
echo $name , ' => ' , $surname , ' => ' , $address , PHP_EOL;
}

Assuming they are all the same length:
for ($i = 0; $i < count($names); $i++) {
echo "{$names[$i]}, {$surnames[$i]}, {$addresses[$i]}";
}

You can do it like that (if arrays have the same keys):
foreach ($name as $key => $value) {
//use $name[$key], $surname[$key], $address[$key]
}
$key contains key in $name array
$value = $name[$key]

Try this
foreach($arr1 as $i => $val) {
var_dump($val, $arr2[$i], $arr3[$i]);
}

If the array keys are the same you can use key() function.
But you can pass the key to foreach($array as $key => value()){}
This way you can refer to the key by the variable without using a function.

Related

Retrieve Highest Value from Array in PHP

I would post the entire code, but it is lengthly and confusing, so I'll keep it short and simple. This is complicated for myself, so any help will be greatly appreciated!
These are the values from my Array:
Light Blue1
Blue2
Blue1
Black3
Black2
Black1
The values I need to retrieve from my Array are "Light Blue1", "Blue2" and "Black3". These are the "highest values" for each color.
Something similar to what I'm looking for is array_unique, but that wouldn't work here. So something along those lines that can retrieve each color with its highest number.
Thanks!
Assuming your format is always NameNumber a regex should do the trick for separating the data. This will loop through your data in the order your provide and grab the first element that is different and put it into $vals. I am also assuming your data will always be ordered as your example shows
$data = ['Light Blue1',
'Blue2',
'Blue1',
'Black3',
'Black2',
'Black1'];
$vals = [];
$current = '';
foreach($data as $row) {
if(!preg_match('/(.*)(\d)/i', $row, $matched)) continue;
if($matched[1] != $current) {
$vals[] = $row;
$current = $matched[1];
}
}
The solution using preg_split and max functions:
$colors = ['Light Blue1', 'Blue2', 'Blue1', 'Black3', 'Black2', 'Black1'];
$unique_colors = $result = [];
foreach ($colors as $k => $v) {
$parts = preg_split("/(\d+)/", $v, 0, PREG_SPLIT_DELIM_CAPTURE);
$unique_colors[$parts[0]][] = (int) $parts[1];
}
foreach ($unique_colors as $k => $v) {
$result[] = $k . max($v);
}
print_r($result);
The output:
Array
(
[0] => Light Blue1
[1] => Blue2
[2] => Black3
)
If you pre-sort your array with "natural sorting", then you can loop through the array and unconditionally push values into the result with digitally-trimmed keys. This will effectively overwrite color entries with lesser number values and only store the the highest numbered color when the loop finishes.
Code: (Demo)
natsort($data);
$result = [];
foreach ($data as $value) {
$result[rtrim($value, '0..9')] = $value;
}
var_export(array_values($result));
Or you could parse each string and compare the number against its cached number (if encountered before): (Demo)
$result = [];
foreach ($data as $value) {
sscanf($value, '%[^0-9]%d', $color, $number);
if (!isset($result[$color]) || $result[$color]['number'] < $number) {
$result[$color] = ['value' => $value, 'number' => $number];
}
}
var_export(array_column($result, 'value'));
A related technique to find the highest value in a group

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.

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 />");
}

Multiple array echo with foreach statement in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiple index variables in PHP foreach loop
Can we echo multiple arrays using single foreach statement?
Tried doing it in following way but wasn't successful:
foreach($cars, $ages as $value1, $value2)
{
echo $value1.$value2;
}
assuming both arrays have the same amount of elements, this should work
foreach(array_combine($cars, $ages) as $car => $age){
echo $car.$age;
}
if the arrays are not guaranteed to be the same length then you can do something like this
$len = max(count($ages), count($cars));
for($i=0; $i<$len; $i++){
$car = isset($cars[$i]) ? $cars[$i] : '';
$age = isset($ages[$i]) ? $ages[$i] : '';
echo $car.$age;
}
if you just want to join the two arrays, you can do it like this
foreach(array_merge($cars, $ages) as $key => $value){
echo $key . $value;
}

Is it possible in PHP for an array to reference itself within its array elements?

I'm wondering if the elements of array can 'know' where they are inside of an array and reference that:
Something like...
$foo = array(
'This is position ' . $this->position,
'This is position ' . $this->position,
'This is position ' . $this->position,
),
foreach($foo as $item) {
echo $item . '\n';
}
//Results:
// This is position 0
// This is position 1
// This is position 2
They can't "reference themselves" per se, and certainly not via a $this->position as array elements are not necessarily objects. However, you should be tracking their position as a side-effect of iterating through the array:
// Sequential numeric keys:
for ($i = 0; $i < count($array); ++$i) { ... }
// Non-numeric or non-sequential keys:
foreach (array_keys($array) as $key) { ... }
foreach ($array as $key => $value) { ... }
// Slow and memory-intensive way (don't do this)
foreach ($array as $item) {
$position = array_search($item, $array);
}
No, PHP's arrays are plain data structures (not objects), without this kind of functionality.
You could track where in the array you are by using each() and keeping track of the keys, but the structure itself can't do it.
As you can see here: http://php.net/manual/en/control-structures.foreach.php
You can do:
foreach($foo as $key => $value) {
echo $key . '\n';
}
So you can acces the key via $key in that example

Categories