how can i use more than one array in foreach()? - php

i want to send more than on array in foreach() .
i know this way is false .whats the true method ?
$Fname = [1,2,3,4,5];
$Lname = [1,2,3,4,5];
$Addrs = [1,2,3,4,5];
$Mobile = [1,2,3,4,5];
$fields = array(
'name' => 'a',
'type' => 'b',
'value' => 'n',
'show' => 'd',
);
foreach($fields as $key => $n)
{
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$key} ,{$n} <br>";
}

If all your arrays have the same number of rows, you can use a for loop instead of a foreach, in conjunction with next() and current() for associative array:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
echo current($fields) . PHP_EOL;
next($fields);
}
The problem is that your arrays haven't same rows number...
So you have to add some condition like this:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
if( isset(current($fields)) )
{
echo current($fields) . PHP_EOL;
next($fields);
}
}

i know this way is false...? What's false about it?
foreach() will iterate over an array, not over multiple arrays.... if you absolutely need to iterate over multiple arrays within the same foreach() loop, you can use SPL's MultipleIterator, but it adds a lot more complexity to your code, and the approach that you've taken is as good as any
Just make sure that your keys match up in all the arrays; if they don't then you will have problems
foreach(array_values($fields) as $key => $n)
{
$k = array_keys($fields)[$key];
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$k} ,{$n} <br>";
}

Instead of storing your data like that, it'd be easier to store it in an array of associative arrays:
$people = array(
array(
'firstName' => 'Bruce',
'lastName' => 'Wayne',
'address' => '123 East St. Gotham City, XX USA'
'mobile' => '847-847-8475'
),
array(
'firstName' => 'Roland',
'lastName' => 'Deschain',
'address' => 'N/A'
'mobile' => '191-919-1919'
)
);
foreach($people as $person){
echo $person['firstName'] + ', ' + $person['lastName'];
echo $person['address'] + ', ' + $person['mobile'];
}
It's just a cleaner way to store/access your data, makes it easy to use one foreach as well.

Try this code
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);
foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}
var_dump($arr1);
var_dump($arr2);

Related

Calculating with multi arrays

I need help with some of my code. I need to use the numbers in prijs for a calculation.
$autos = array(
"<b>Mercedes</b>" =>array(
"Kenteken" => "77NLXJ",
"Prijs" => "54800",
),
"<b>Tesla</b>" =>array(
"Kenteken" => "GV713G",
"Prijs" => "70700",
),
"<b>Porsche</b>" =>array(
"Kenteken" => "GG101K",
"Prijs" => "85000",
)
Is this possible?
$keys = array_keys($autos);
for($i = 0; $i < count($autos); $i++) {
echo $keys[$i] . "<br>";
foreach($autos[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "<br>";
}
To access and change them, you need to access them through the $autos array:
//by loop:
foreach($autos as $key => $auto){
//get or set them with this var
$autos[$key]["Prijs"];
}
//to get and set them directly:
$autos[0]["Prijs"];
$autos[1]["Prijs"];
$autos[2]["Prijs"];

How do i loop through an array with for loop

<?php
$people = array(
'maurice' => array ('name' => 'hillary',
'age' =>20,
'education'=>'degree'),
'george' => array ('name' => 'florence',
'age' =>30,
'education'=>'diploma'),
'Michael' => array ('name' => 'Andrew',
'age' =>10,
'education'=>'certificate')
);
$countp = count($people);
//echo $people['maurice']['name'];
for ($i=0; $i < $countp; $i++) {
for ($j=0; $j < $countp[$i]; $j++) {
for ($k=0; $k < $countp[$i][$j]; $k++) {
echo $people[$i][$j][$k].'<br />';
}
}
# code...
}
?>
i am trying to loop through a multidimensional array with a for loop what could be the problem here. i have shared the code above.
You should use foreach
foreach($people as $name=>$information){
foreach($information as $informationKey=>$informationValue){
echo $informationValue;
}
}
Your array is not made of integer indices. It is make of keys.
How about we rewrite your for loop
foreach ($people as $person => $data) {
echo $person . PHP_EOL;
echo "Name : " .$data['name'] . PHP_EOL;
echo "Age : " .$data['age'] . PHP_EOL;
echo "Education : " .$data['education'] . PHP_EOL;
}
That shoud make it better!
You are using strings as keys (instead of integers), so you need to access the array like $people['maurice']['name'], instead of $people[0][0].
You only have two dimensions, so you don't need three loops
You should use foreach() http://php.net/manual/en/control-structures.foreach.php

Creating key value pairs using next two iterations in a for loop (PHP)

I have an array of string values called $genderAge that looks like this when echoed:-
F, 0-4, 327607378
M, 0-4, 392700793
F, 15-24, 887438943
M, 15-24, 525132614
M, 25-34, 621410857
So for the above array, $ageRange[0] is "F". $ageRange[1] is "0-4", and so forth.
I want to separate it out into two arrays, $male_array and $female_array with key value pairs. The key should be age range and the value should be cost.
$male_array = [];
$female_array = [];
for ($i = 0; $i < count($genderAge); $i++) {
if ($genderAge[i] == 'M') {
$male_array[$genderAge[i+1]] = $genderAge[i+2];
}
elseif ($genderAge[i] == 'F') {
$female_array[$genderAge[i+1]] = $genderAge[i+2];
}
}
foreach($male_array as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
The above doesn't echo anything. I want it to echo this:
Key=0-4, Value=392700793
Key=15-25, Value=525132614
Key=25-34, Value=621410857
Your $genderAge should be an array of this kind so that you can perform storing of values in the separate variables and you can use it for further purpose.
Proposed Array:
$genderAge = array("F", "0-4", "327607378", "M", "0-4", "392700793", "F", "15-24", "887438943","M", "15-24", "525132614","M","25-34", "621410857");
For Loop Manipulation over the array in order to save the value.
Here you must use $i for increment operator with +1. You must not use the i along separately as you have used.
PHP Code:
<?php
$genderAge = array("F", "0-4", "327607378", "M", "0-4", "392700793", "F", "15-24", "887438943","M", "15-24", "525132614","M","25-34", "621410857");
$male_array = [];
$female_array = [];
for ($i = 0; $i < count($genderAge); $i++) {
if ($genderAge[$i] == 'M') {
$male_array[$genderAge[$i+1]] = $genderAge[$i+2];
}
elseif ($genderAge[$i] == 'F') {
$female_array[$genderAge[$i+1]] = $genderAge[$i+2];
}
}
echo 'M Values'.'<br>';
foreach($male_array as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo '<br>';
echo 'F Values'.'<br>';
foreach($female_array as $y=> $y_value) {
echo "Key=" . $y . ", Value=" . $y_value;
echo "<br>";
}
echo '<br>';
?>
Output:
M Values
Key=0-4, Value=392700793
Key=15-24, Value=525132614
Key=25-34, Value=621410857
F Values
Key=0-4, Value=327607378
Key=15-24, Value=887438943
If your array is constantly a combination of 3 pairs : Gender, Age range, Cost, you may want to increment of each 3 pairs in your loop. It will save you from errors relative to out of array indexes :
<?php
$GENDER_MALE = 'M';
$GENDER_FEMALE = 'F';
$genderAge = ['F', '0-4', '327607378', 'M', '0-4', '392700793', 'F', '15-24', '887438943', 'M', '15-24', '525132614', 'M', '25-34', '621410857'];
$male_array = [];
$female_array = [];
$size = count($genderAge);
# Format the male/female array
for( $i = 0; $i < $size; $i += 3 ) {
$gender = $genderAge[$i]; // M or F
$ageRange = $genderAge[$i + 1]; // 0-4, 14-18, ...
$cost = $genderAge[$i + 2]; // 897726, 10927, ...
if( $gender == $GENDER_MALE ) {
$male_array[$ageRange] = $cost;
}
else if( $gender == $GENDER_FEMALE ) {
$female_array[$ageRange] = $cost;
}
}
# Print the male/female formatted array
foreach( $male_array as $key => $value ) {
echo "Age range : $key - cost = $value <br />";
}
?>
Notice in the first for loop the use of $i += 3 which can be read as :
Loop every 3 items on my array
This way, you can apply your index + n relative to the pair you need ($i + 1 for the age range, and so on).
First, You may want to get all those key-value pairs including the Sex in an associative array, instead. Here's how that could be done using for(){} Loop:
<?php
$arr = array("F"," 0-4", "327607378",
"M", "0-4", "392700793",
"F", "15-24", "887438943",
"M", "15-24", "525132614",
"M", "25-34", "621410857");
$all = array();
for($a=0, $b=1, $c=2; $a <= (count($arr)-3); $a+=3, $b+=3, $c+=3){
$temp = array(
"sex" => $arr[$a],
"key" => $arr[$b],
"value" => $arr[$c]
);
$all[] = $temp;
}
var_dump($all);
The call to var_dump($all); yields:
array (size=5)
0 =>
array (size=3)
'sex' => string 'F' (length=1)
'key' => string ' 0-4' (length=4)
'value' => string '327607378' (length=9)
1 =>
array (size=3)
'sex' => string 'M' (length=1)
'key' => string '0-4' (length=3)
'value' => string '392700793' (length=9)
2 =>
array (size=3)
'sex' => string 'F' (length=1)
'key' => string '15-24' (length=5)
'value' => string '887438943' (length=9)
3 =>
array (size=3)
'sex' => string 'M' (length=1)
'key' => string '15-24' (length=5)
'value' => string '525132614' (length=9)
4 =>
array (size=3)
'sex' => string 'M' (length=1)
'key' => string '25-34' (length=5)
'value' => string '621410857' (length=9)
Now, to echo out some data, you can just do something like this:
<?php
foreach($all as $iKey=>$arrKv){
echo "sex : " . $arrKv["sex"] . "<br />" . PHP_EOL;
echo "Key : " . $arrKv["key"] . "<br />" . PHP_EOL;
echo "Value : " . $arrKv["value"] . "<br /><br />" . PHP_EOL;
}
The Compound Result of each of the echo() in the Loop above yields:
sex : F
Key : 0-4
Value : 327607378
sex : M
Key : 0-4
Value : 392700793
sex : F
Key : 15-24
Value : 887438943
sex : M
Key : 15-24
Value : 525132614
sex : M
Key : 25-34
Value : 621410857

How to auto increment in sub foreach loop?

Here is the example code:
<?php
$arr = array(
array(
'company' => array(
'code' => 'ccd1',
'name' => 'cnm1'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
)
)
) ,
array(
'company' => array(
'code' => 'ccd2',
'name' => 'cnm2'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
) ,
array(
'code' => 'pcd3',
'name' => 'pnm3'
)
)
)
);
echo "<pre>"; print_r($arr); echo "</pre>";
$AI = 1;
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
foreach($value['products'] as $value2){
echo " ".$value2['name']."<br />";
}
}
I don't know how to explain it, but what I want is to add auto increment in sub foreach loop, like this:
1.cnm1 (2)
1.pnm1
2.pnm2
2.cnm2 (3)
1.pnm1
2.pnm2
3.pnm3
Usually you can just use the foreach keys plus one. As another alternative, if this is just for presentation, just use ordered lists:
echo '<ol>';
foreach($arr as $ar1) {
echo '<li>' . $ar1['company']['name'] . ' (' . count($ar1['products']) . ')</li>';
echo '<ol>';
foreach($ar1['products'] as $ar2) {
echo "<li>{$ar2['name']}</li>";
}
echo '</ol>';
}
It'll number those items accordingly. No need for addition. Plus you can use CSS to style the list,
You can access the key/index of an foreach :
foreach($arr as $i => $value){
$total_products = count($value['products']);
echo ($i+1).'.'.$value['company']['name'].' ('.$total_products .')<br />';
foreach($value['products'] as $j => $value2){
echo ' '.($j+1).'.'.$value2['name'].'<br />';
}
}
Here you go.
$arr = array(array('company'=>array('code'=>'ccd1', 'name'=>'cnm1'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'))), array('company'=>array('code'=>'ccd2', 'name'=>'cnm2'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'), array('code'=>'pcd3', 'name'=>'pnm3'))));
echo "<pre>";
print_r($arr);
echo "</pre>";
$AI = 1;
foreach($arr as $value)
{
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$k = 0;
foreach($value['products'] as $value2)
{
echo " ".$k++.". ".$value2['name']."<br />";
}
}
This also worked for me:
foreach($value['products'] as $key2=>$value2){
$AI2 = $key2+1;
echo " ".$AI2.".{$value2['name']}<br />";
}
You can try this:
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$sub=1;
foreach($value['products'] as $value2){
echo " ".$sub++.'.'.$value2['name']."<br />";
}
}

Sorting arrays by value

I have this post array
Array (
[imgurl_3] => http://localhost/wordpress/wp-content/uploads/2014/03/05-239x300.jpg
[imgtekst_3] => Write a text for the slide
[imgurl_4] => http://localhost/wordpress/wp-content/uploads/2014/03/img_2184-300x225.jpg
[imgtekst_4] => Write a text for the slide
[update_gallery] => Save changes )
The numbers in the end of the imgurl and imgtekst are dynamic. So.
I want to pair the imgurl_3 & imgtekst_3, and so on. To update into a database.
Any smart PHP functions for this?
Thanks
$array = [
'imgurl_3' => 'http://localhost/wordpress/wp-content/uploads/2014/03/05-239x300.jpg',
'imgtekst_3' => 'Write a text for the slide',
'imgurl_4' => 'http://localhost/wordpress/wp-content/uploads/2014/03/img_2184-300x225.jpg',
'imgtekst_4' => 'Write a text for the slide',
'update_gallery' => 'Save changes'
];
$output = [];
foreach ($array as $key => $item) {
$intKey = filter_var($key, FILTER_SANITIZE_NUMBER_INT);
if ($intKey) {
$key = preg_replace('/_\d/', '', $key);
$output[$intKey][$key] = $item;
}
}
print_r($output);
You could use a for loop and select correlated entries:
for($i = 0; $i < $whatever; $i++) {
if(array_key_exists('imgurl_' . $i, $array)) {
$value = $array['imgurl_' . $i];
$value2 = $array['imgtekst_' . $i];
}
$sqlQuery = '<UPDATE using $value and $value2>';
}

Categories