Array replace not working - php

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);

Related

Increment Value $k use Array Insert loop

I need to increase the value of the $ k variable every time a record of that loop is inserted in order to insert the array I have with the necessary values. Here I leave a part of the code to see if you can help me.
$k = 0;
foreach ($detalles as $d) {
$num = $d['stock'];
$val = floor($num/$limite);
for($i=0;$i<$limite;$i++) {
$arr[$i] = $val;
}
$arr[0] += $num - array_sum($arr);
$this->transac_detail_temp->save([
'id_trx_header'=> $id,
'producto' => $d['id_producto'],
'cantidad' => $arr[$k]++,
'tipo_transaccion'=> 2]
);
} // foreach detalles
I am not sure about your question but hope this will be you
Replace this code
'cantidad' => $arr[$k]++,
to
'cantidad' => $arr[$k],
and this code in last section
$k++;
so final code will be like this
$k = 0;
foreach ($detalles as $d) {
$k++; //added
//echo $k."<br>"; // if you want to check update value of $k
$num = $d['stock'];
$val = floor($num/$limite);
for($i=0;$i<$limite;$i++) {
$arr[$i] = $val;
}
$arr[0] += $num - array_sum($arr);
$this->transac_detail_temp->save([
'id_trx_header'=> $id,
'producto' => $d['id_producto'],
'cantidad' => $arr[$k], //update
'tipo_transaccion'=> 2]
);
}

Dynamically populate php array using foreach loop

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);

Undefined Offset PHP error, arrays are defined

Getting an Undefined Offset error here -- apparently from the $newval array.
Note that the {exp} tag is not PHP, and is simply a sql query by my CMS system which creates the $bags array for me.
<?php
$bags = array();
$newval = array();
$pattern = "[^0-9]";
{exp:query sql="SELECT m_field_id_1 as bags FROM exp_member_data WHERE m_field_id_1 IS NOT NULL"}
$bags[] = "{bags}";
{/exp:query}
foreach ($bags as $key => $value) {
for ( $i = 0, $s = strlen($value); $i < $s; $i++) {
if ( is_numeric($value[$i]) ) {
$newval[$key] .= $value[$i];
}
}
}
$sum = array_sum($newval);
$format = number_format($sum);
echo $format;
?>
Before you can concatenate to a variable, that variable must exist (to avoid a Notice). Simply declare $newval[$key] as an empty string before the for loop:
foreach ($bags as $key => $value) {
$newval[$key] = '';
for ($i = 0, $s = strlen($value); $i < $s; $i++) {
if ( is_numeric($value[$i]) ) {
$newval[$key] .= $value[$i];
}
}
}
By the way, there's nothing wrong with your starting value of $i. It is correct to have it at 0 and not 1 as others are suggesting.
However, if you're trying to remove non-number characters from a string and avoid empty array elements (as your original code does), you can remove the inner for loop and simply:
foreach ($bags as $key => $value) {
$digits = preg_replace('/[^0-9]/', '', $value);
if (strlen($digits)) {
$newval[$key] = $digits;
}
}
As Jrod said you're walking through the characters in $value but you start at 0. strlen() returns the absolute amount of chars in $value so in your for loop you should start at 1 instead of 0.
This is the code you should use:
<?php
$bags = array();
$newval = array();
$pattern = "[^0-9]";
{exp:query sql="SELECT m_field_id_1 as bags FROM exp_member_data WHERE m_field_id_1 IS NOT NULL"}
$bags[] = "{bags}";
{/exp:query}
foreach ($bags as $key => $value) {
$newval[$key] = '';
for ( $i = 1, $s = strlen($value); $i < $s; $i++) {
if ( is_numeric($value[$i]) ) {
$newval[$key] .= $value[$i];
}
}
}
$sum = array_sum($newval);
$format = number_format($sum);
echo $format;
?>
Instead of this
foreach ($bags as $key => $value) {
for ( $i = 0, $s = strlen($value); $i < $s; $i++) {
if ( is_numeric($value[$i]) ) {
$newval[$key] .= $value[$i];
}
}
}
you can write
$newval = preg_replace('~\D+~', '', $bags);
one line is easier to debug than six, isn't it.

How to convert every two consecutive values of an array into a key/value pair?

I have an array like the following:
array('category_name:', 'c1', 'types:', 't1')
I want the alternate values of an array to be the values of an array:
array('category_name:' => 'c1', 'types:' => 't1')
You could try: (untested)
$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
$key = $data[$i];
$value = $data[$i+1];
$output[$key] = $value;
}
Alternatively: (untested)
$output = Array();
foreach($data as $key => $value):
if($key % 2 > 0) { //every second item
$index = $data[$key-1];
$output[$index] = $value;
}
endforeach;
function fold($a) {
return $a
? array(array_shift($a) => array_shift($a))
+ fold($a)
: array();
}
print_r(fold(range('a','p' )));
~)
upd: a real-life version
function fold2($a) {
$r = array();
for($n = 1; $n < count($a); $n += 2)
$r[$a[$n - 1]] = $a[$n];
return $r;
}
Here is another yet complex solution:
$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];

PHP: simple array operation

I have an array like this (one dimension only):
$arr = array('one', 'two', 'three', 'foo', 'bar', 'etc');
Now I need a for() loop that creates a new array from $arr, like that:
$newArr = array('one', 'onetwo', 'onetwothree', 'onetwothreefoo', 'onetwothreefoobar', 'onetwothreefoobaretc');
Seems to be simple but I can't figure it out.
Thanks in advance!
$mash = "";
$res = array();
foreach ($arr as $el) {
$mash .= $el;
array_push($res, $mash);
}
$newArr = array();
$finish = count($arr);
$start = 0;
foreach($arr as $key => $value) {
for ($i = $start; $i < $finish; $i++) {
if (isset($newArray[$i])) {
$newArray[$i] .= $value;
} else {
$newArray[$i] = $value;
}
}
$start++;
}

Categories