Dynamically populate php array using foreach loop - php

How can I implement the code:
$numberList3 = array();
for($i = 0; $i < 10; $i++)
{
$numberList3[$i] = $i;
}
print_r($numberList3);
Using a foreach loop as the no. of times the loop is going to execute is decided by the user at run time.
Any suggestion.?

Use array_fill maybe?
<?php
$n = 10;
$arr = array_fill(0,$n,0);
foreach($arr as $k => $v) {
$arr[$k] = $k;
}
print_r($arr);
Or, as suggested by #deceze, use range
<?php
$n = 10;
$arr = array();
foreach(range(0,$n-1) as $v) {
$arr[$v] = $v;
}
print_r($arr);
Or when the value is the same as the key, you can use just this:
<?php
$n = 10;
$arr = range(0,$n-1);
// no foreach needed
print_r($arr);

foreach() works for object and array not for a single value.
What you can do create an array or object from users input.
like:
$userInput = 10;
$forEachArray = array_fill(0, $userInput, 0);
$arrayToDisplay = array();
foreach($forEachArray as $key){
$arrayToDisplay[$key] = $key;
}
print_r($arrayToDisplay);

Related

PHP array keys as nth value

I have an Associative array as
$array = Array([0]=>a[1]=>b[2]=c[3]=>d);
I need to build an array from this array where the the first key becomes a and the value becomes b & 2nd key becomes c and value becomes d.
Output should be:
$finalarray = Array([a]=>b,[c]=>d);
I have tried this following code:
foreach($array as $key=>$value){
$arr[$value] = array_slice($array, 1, 1);
$finalarray[] = $arr;
}
Please help me with this!
The best way is to loop on your first array, but to skip one value on two:
$array = array("a", "b", "c", "d");
$finalArray = array();
for ($i = 0; $i < count($array); $i+=2) {
$finalArray[$array[$i]] = $array[$i + 1];
}
This may help:
$a = array('a','b','c','d'); $b = array();
$length = count(a)%2 ? count($a)-1 : count($a);
for($i=0; $i<$length; $i++){
$b[$a[$i]] = $a[++$i];
}
var_dump($a,$b);
Little changed your code:
$i=0;
foreach($array as $key=>$value){
$value_2=$value++;
if($i%2==0)
$arr[$value_2] =$value;
$i++;
//$finalarray[] = $arr;
}
echo"<pre>";
print_r($arr);
If your array is associative , below code may help you
<?php
$array = array(0=>'a',1=>'b',2=>'c',3=>'d');
$new_array = array();
for($i=0;$i<count($array);$i+=2)
{
$new_array[$array[$i]] = $array[$i+1];
}
print_r($new_array);
?>

Multiplying a 2d array by a 1d array in PHP using foreach

let me start off by saying what I have works just fine. However, I was wondering if there was a method using foreach loops, instead of while loops, that will return the same result. My current code is:
$a[0] = $_GET['a1'];
$a[1] = $_GET['a2'];
$a[2] = $_GET['a3'];
$a[3] = $_GET['a4'];
$a[4] = $_GET['a5'];
$a[5] = $_GET['a6'];
$a[6] = $_GET['a7'];
$a[7] = $_GET['a8'];
$a[8] = $_GET['a9'];
$a[9] = $_GET['a10'];
$a[10] = $_GET['a11'];
$a[11] = $_GET['a12'];
$a[12] = $_GET['a13'];
$a[13] = $_GET['a14'];
$a[14] = $_GET['a15'];
$a[15] = $_GET['a16'];
$a[16] = $_GET['a17'];
$a[17] = $_GET['a18'];
$a[18] = $_GET['a19'];
$a[19] = $_GET['a20'];
$a[20] = $_GET['a21'];
$a[21] = $_GET['a22'];
$a[22] = $_GET['a23'];
$a[23] = $_GET['a24'];
$a[24] = $_GET['a25'];
$a[25] = $_GET['a26'];
$a[26] = $_GET['a27'];
$a[27] = $_GET['a28'];
$array1 = array(
array(-0.0165333833412173,-0.805148897111146,-0.253228140499216,-0.184436610496828,-0.182460815146422,-0.562680616467753),
array(0.0530980021095432,0.197367160352892,0.486754591654999,0.100148472516492,0.129649075750223,-0.0891313538023273),
array(1.20820560236013,1.60297691019929,1.88645801788488,1.4097784563,1.35491780171462,1.83839262576814),
array(0.35474704442591,0.669288291278341,-0.618871707987998,0.314393917137463,0.369309934864932,0.302877707428276),
array(1.73737846681824,1.23045039205127,1.74985170545799,2.53444768504332,0.947425891979588,2.49693773110446),
array(1.08515864048978,1.19974869194067,1.40391203998614,0.645993089768699,1.18500365352365,0.183710871687018),
array(-0.158201130751605,0.245894811416122,-0.13491139550657,0.268781009345758,0.584094496717681,-0.475038989317082),
array(2.69120997158388,2.6335032877555,2.1678974119528,1.98159587601917,2.47871441914596,3.11218576826585),
array(1.58301428618536,1.4690581543491,1.64181831092486,1.31270093574087,0.956030437566211,1.68095459548238),
array(0.567053945109392,0.672686283651576,0.50520628014895,0.573859412747649,0.906581004455213,0.675935843127413),
array(2.21154924140175,2.4629227185282,2.44302564998387,1.76594656224375,2.24292394905905,2.46555856986067),
array(0.789058773638184,0.56494483459565,1.02220848055446,0.740827710977414,0.0568788365193514,0.974084436394248),
array(-1.22527151151768,-0.37116067796664,-0.993915606653743,-0.265414040283105,-0.0483919594705323,-1.26478189171631),
array(1.93198111668015,0.978691339072353,0.896606685235391,1.43344220993764,1.44428119515243,0.832846974841109),
array(0.0960968892129648,0.179429676667834,0.653561055735465,0.611111687937286,0.420917607921928,0.788124847059183),
array(-0.570188484564322,-0.367869613869776,-0.425708923999659,0.58428081962228,0.431696028180505,-0.560777966949268),
array(2.18753554884398,2.10453220450978,2.18396016604212,1.53663043726462,1.6128493800773,2.47023229651768),
array(0.933680338305853,0.701683572817621,1.05817969240128,1.13326689801564,1.06305023491714,1.28172788495342),
array(0.237030103809889,1.19429662809383,1.32352397170755,0.787441428409051,1.06861486730769,0.196323518345157),
array(1.27102015175144,0.999617071482296,1.14337292692749,1.79352497701309,1.14261585172827,1.18874166503307),
array(0.746730730970985,0.584005303699165,0.00845233248507581,0.617844244971367,0.646839413026708,0.393004935019083),
array(1.33877796293032,1.18403793988876,1.16686497194317,1.18487924665819,0.796233877768925,1.21668080067963),
array(1.66146357909026,1.52622605987311,1.51673796371559,2.45659237209795,1.58826974938031,1.87667392945756),
array(1.23205756178945,1.25461474916892,1.0738857243227,1.21949513612512,0.847503017550969,1.33075294766838),
array(0.976236852070675,1.0676137689421,1.08390543200419,1.19114160706157,0.804407032221587,0.918305581716723),
array(1.0514345299356,1.24825633668808,1.15750685444102,1.34538988886631,1.24490007119083,0.994386901437322),
array(-50.5445732202499,-53.6034355984409,-52.2301074110166,-59.4416059910645,-50.3559798265968,-51.5135149950383),
);
$array2 = array();
$x = 0;
while($x < COUNT($array1)){
$y = 0;
while($y < COUNT($array1[$x])){
$array2[$x][$y] = $array1[$x][$y] * $a[$x];
//echo($array2[$x][$y] . ', ');
$y++;
}
//echo('<br>');
$x++;
}
Again, while this works, I am trying to get into the habit of writing cleaner code. Additionally, I am still relatively new to PHP, so I'm still struggling a bit with some of its syntax and structuring.
Thanks in advance.
This should work identical to what you have.
$array2 = array();
foreach($a as $k1=>$a1)
{
foreach($array1[$k1] as $k2=>$a2)
{
$array2[$k1][$k2] = $a2 * $a1;
}
}
The basic format of a foreach loop is foreach($array as $key=>$value) if you don't need the array key, you can shorten it to foreach($array as $value).
You can reduce the code by directly accessing the $_GET values instead of copying them into $a.
$result = array();
foreach($array1 as $k1 => $array2) {
foreach($array2 as $k2 => $value) {
$result[$k1][$k2] = $value * $_GET['a'.($k1+1)];
}
}

Array replace not working

The below is my array, where I need to replace the value of 'battle_health'
$battlepokemon= array();
$i = 1;
while($rows = mysql_fetch_assoc($res))
{
$path = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$rows['pkmn_id']."' ");
$pokemon = array(
'opponent_increment' => $i,
'id' => $rows['pkmn_id'],
'battle_poke'=> mysql_result($path,0,"path"),
'battle_level' => $rows['level'],
'battle_health' => $rows['health']
);
$i++;
$battlepokemon[]= $pokemon;
}
The code for replacement is:
$i = 1;
foreach ($battlepokemon as $key => $value)
{
if($value['opponent_increment'] == $opponent_increment)
{
$value['battle_health'] = 0;
echo "Data replaced!";
}
$i++;
}
print_r($battlepokemon);
The code above is working..from start to end.. but the value is not replaced with '0' as the code says!
I think I must have missed something!
You need to transfer the reference, not the values. Add a & to the following sentence
foreach ($battlepokemon as $key => &$value)
^
I tried this just for example
<?php
$arr = array('12', '34');
foreach($arr as $key => &$value){
$value = 0;
}
var_dump($arr);
?>
Hopes it can help you
You can achieve this with for Loop Because unlike foreach loop, it doesn't perform an array copy before transversal:
$arr = array('12', '34');
for($i = 0, $count = count($arr); $i < $count; $i++){
$arr[$i] = 0;
}
var_dump($arr);
Or If you want to do with Foreach only, you need to avoid new copy of array by passing the reference like:
$arr = array('12', '34');
foreach($arr as $key => &$value)
{
$value = 0;
}
var_dump($arr);

How do I select random values from an array in PHP?

I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.
I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?
$result = array();
foreach( array_rand($my_array, 8) as $k ) {
$result[] = $my_array[$k];
}
$array = array();
shuffle($array); // randomize order of array items
$newArray = array_slice($array, 0, 8);
Notice that shuffle() function gives parameter as a reference and makes the changes on it.
You could use array_rand to pick the keys randomly and a foreach to gather the objects:
$objects = array();
foreach (array_rand($my_array, 8) as $key) {
$objects[] = $my_array[$key];
}
What about?:
$count = count($my_array);
for ($i = 0; $i < 8; $i++) {
$x = rand(0, $count);
$my_array[$x];
}
I just found this in our code and was hoping to find a more readable solution:
$rand = array_intersect_key($all, array_flip(array_rand($all, $count)));
You can get multiple random elements from an array with this function:
function getRandomElements(array $array): array
{
$result = [];
$count = count($array);
for ($i = 0; $i < rand(0, $count); $i++) {
$result[] = rand(0, $count);
}
$result = array_unique($result);
sort($result);
return $result;
}

PHP Multidimensional Array - "Exchange" Dimensions

I'm wondering what the best way is of doing this:
$fc['abc'][0] = 1;
$fc['xyz'][0] = 2;
$fc['abc'][1] = 3;
$fc['xyz'][1] = 4;
$fc2 = something($fc);
print $fc2[0]['abc']; // 1
In other words, the something function will swap the two dimensions round.
There is probably a more elegant way of doing this, but this works:
$result = array();
foreach ($fc as $key1 => $arr) {
foreach ($arr as $key2 => $num) {
$result[$key2][$key1] = $num;
}
}
array_flip() ?
http://php.net/manual/en/function.array-flip.php

Categories