PHP variables not changing outside of function - php

I have a function in PHP. I am passing two arrays to the function as references. While the function updates $array2 outside the function, it does not update $array. Below is my function.
function JobAssign($i,&$array,&$array2,$Machine_Interchange) {
$compmachine = $array[$i]['Machine_Name'];
$CLT = $array[$i]["Estimated_Start_Date"];
$ET = $array[$i]["Estimated_Completion_Date"];
$Machine = $array[$i]['Machine_Name'];
$Compatibility_sql = "SELECT Machine2 FROM Machine_Interchange where Machine1 = '$Machine' and Value = 1";
$compatibility_query = mysql_query($Compatibility_sql) or die(mysql_error());
for($i=0; $compatibility[$i] = mysql_fetch_assoc($compatibility_query);$i++);
array_pop($compatibility);
$maxkey = max(array_keys($compatibility));
$maxnumber = max(array_keys($array2))+1;
$k=0;
do{
$compmachine = $compatibility[$k]['Machine2'];
$CLT = $array2[$compmachine];
if($array2[$compatibility[$k]['Machine2']]>$array2[$compatibility[$k+1]['Machine2']]) {
$compmachine = $compatibility[$k+1]['Machine2'];
$CLT = $array2[$compatibility[$k+1]['Machine2']];
}
$k=$k+1;
}
while($k<$maxkey);
$array[$i]["Machine_Name"] = $compmachine;
$array[$i]["Estimated_Start_Date"] = $CLT;
$prodhours = $array[$i]["Prod_Hrs"];
$array[$i]["Estimated_Completion_Date"] = date('Y-m-d H:i:s', strtotime($CLT . " +$prodhours hour"));
$array2[$compmachine] = $array[$i]["Estimated_Completion_Date"];
echo $array[$i]['Machine_Name'].'<br>';
echo $array[$i]['Estimated_Start_Date'].'<br>';
echo $array[$i]['Estimated_Completion_Date'].'<br>';
echo $array2[$compmachine].'<br>';
}
JobAssign(0,$Jobs_Data,$LT,$Machine_Interchange);
echo $Jobs_Data[0]['Machine_Name'].'<br>';
echo $Jobs_Data[0]['Estimated_Start_Date'].'<br>';
echo $Jobs_Data[0]['Estimated_Completion_Date'].'<br>';
echo $LT['Machine 3'];
Below is the output that I get.The first 4 lines of the output are from within the function and the next 4 are from outside the function.
Machine 3
2014-07-12 00:00:00
2014-07-15 11:00:00
2014-07-15 11:00:00
Machine 1
2014-07-30 00:00:00
2014-08-02 00:00:00
2014-07-15 11:00:00
When I echo the changed variables inside the function they do change but when I echo $arrayoutside of the function it does not change the values for $array. Only the values for $array2 have changed even though I have passed both arrays as reference in the function arguments. Which means that the line 4 and 8 are the same in the output which means that values for $array2 have changed but not for $array.

Try changing the variable $i on your for loop to another variable. Because it changes the value of the variable while it is looping.
function JobAssign($i,&$array,&$array2,$Machine_Interchange)
{
$compmachine = $array[$i]['Machine_Name'];
$CLT = $array[$i]["Estimated_Start_Date"];
$ET = $array[$i]["Estimated_Completion_Date"];
$Machine = $array[$i]['Machine_Name'];
$Compatibility_sql = "SELECT Machine2 FROM Machine_Interchange where Machine1 = '$Machine' and Value = 1";
$compatibility_query = mysql_query($Compatibility_sql) or die(mysql_error());
for($ii=0; $compatibility[$ii] = mysql_fetch_assoc($compatibility_query);$ii++);
array_pop($compatibility);
$maxkey = max(array_keys($compatibility));
$maxnumber = max(array_keys($array2))+1;
$k=0;
do{
$compmachine = $compatibility[$k]['Machine2'];
$CLT = $array2[$compmachine];
if($array2[$compatibility[$k]['Machine2']]>$array2[$compatibility[$k+1]['Machine2']])
{
$compmachine = $compatibility[$k+1]['Machine2'];
$CLT = $array2[$compatibility[$k+1]['Machine2']];
}
$k=$k+1;
}
while($k<$maxkey);
$array[$i]["Machine_Name"] = $compmachine;
$array[$i]["Estimated_Start_Date"] = $CLT;
$prodhours = $array[$i]["Prod_Hrs"];
$array[$i]["Estimated_Completion_Date"] = date('Y-m-d H:i:s', strtotime($CLT . " +$prodhours hour"));
$array2[$compmachine] = $array[$i]["Estimated_Completion_Date"];
echo $array[$i]['Machine_Name'].'<br>';
echo $array[$i]['Estimated_Start_Date'].'<br>';
echo $array[$i]['Estimated_Completion_Date'].'<br>';
echo $array2[$compmachine].'<br>';
}

The $array is changed as it should, the problem is that is changed in the wrong index.
Explanation:
You call the function with $i = 0 but $i is also used in the loop statement and exits the loop with a different value.
here is the line:
for($i=0; $compatibility[$i] = mysql_fetch_assoc($compatibility_query);$i++);
after the above $i is no longer 0 (as long as you have something to fetch)
So the index of $array that you echo inside the function is different from the index of $array you echo outside the function.
To fix your problem just change the variable of the above loop to something else, let's say $j:
for($j=0; $compatibility[$j] = mysql_fetch_assoc($compatibility_query);$j++);
so that no longer affects $i

Related

Comparing two diffrent arrays returns empty array problem PHP

Hello I made a code which I don't understand why doesn't work, please share a tips with me:
In the end, arrays $recordHited and $logArray I want to compare and count the amount of different elements.
Unfortunately $result = array_diff($recordHited, $logArray); is giving a empty array :-(.
Than you in advance for any tips.
fgets(STIDIN) :
4 2
6
1 1 3 4 1 2
$input_line = trim(fgets(STDIN));
$firstLine = explode(" ",$input_line);
$keyboard = $firstLine[0];
$keyboardArray = array();
$mistakes = $firstLine[1];
$collectArray = array();
$adder = 0;
$recordHited = array();
$endOfArrayValue = 0;
//getting second and third line of innput
for($ix=0;$ix<2;$ix++){
$collectArray[]= trim(fgets(STDIN));
}
//getting line of buttons
for($iy=0;$iy<$keyboard;$iy++){
$adder++;
array_push($keyboardArray,$adder);
}
//declaring the from loop values
$times = $collectArray[0];
$log = $collectArray[1];
$logArray = explode(" ",$log);
//new array of hit
for($k=0;$k<$times;$k++){
if($endOfArrayValue<$keyboard){
$recordHited[]=$keyboardArray[$endOfArrayValue];
$endOfArrayValue++;
}else{
$endOfArrayValue = 0;
$recordHited[]=$keyboardArray[$endOfArrayValue];
$endOfArrayValue++;
};
};
//change array values
$recordHited = array_map('strval', $recordHited);
//print outcome
$result = array_diff($recordHited, $logArray);
echo var_dump($result);
echo var_dump($recordHited);
echo var_dump($logArray);
$sa = count($result);
if($sa>$mistakes){
echo "-1";
}else{
echo (($times-$sa)*1000);
}
?>

PHP loop to read from SQLite and write to arrays/JSON

I have a SQLite3 database which contains 4 tables with 9 rows each.
I've tried to do each one of the arrays one-by-one, with basically the same code as below (everything in the foreach loop), and it worked fine. I guess I just made some stupid mistakes (I don't really use PHP, this is pretty much the only project I've used it in). I tried to fix it, but somehow PHP is not really friendly today.
Currently the code below returns a JSON with 4 empty arrays.
<?php
header('Content-type: application/json');
$db = new PDO('sqlite:whad.db')or die('Could not open database');
$arDaniel = array();
$arAndi = array();
$arDave = array();
$arSimon = array();
for ($j=0; $j < 4; $j++) {
$name;
$arr;
if (j == 0) {
$name = 'Daniel';
$arr = $arDaniel;
}
elseif (j == 1) {
$name = 'Andi';
$arr = $arAndi;
}
elseif (j == 2) {
$name = 'Dave';
$arr = $arDave;
}
elseif (j == 3) {
$name = 'Simon';
$arr = $arSimon;
}
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$i = 1;
foreach($res = $db->query($query) as $value) {
$curr = array();
array_push($curr["Datum"] = $value[0]);
array_push($curr["ID"] = $value[1]);
array_push($curr["RR"] = $value[2]);
array_push($curr["RL"] = $value[3]);
array_push($curr["KB"] = $value[4]);
array_push($curr["BD"] = $value[5]);
array_push($curr["SD"] = $value[6]);
array_push($curr["KH"] = $value[7]);
array_push($curr["Reihenfolge"] = $value[8]);
array_push($arr[$i] = $curr);
$i++;
}
}
$json = array(
"Daniel" => $arDaniel,
"Andi" => $arAndi,
"Dave" => $arDave,
"Simon" => $arSimon
);
echo json_encode($json);
$db = NULL;
?>
EDIT: Removed quotes around $curr.
You have many unnecassary variables with the same data.
You simply could do the following
<?php
header('Content-type: application/json');
$db = new PDO('sqlite:whad.db')or die('Could not open database');
$json = array(
"Daniel" => array(),
"Andi" => array(),
"Dave" => array(),
"Simon" => array()
);
foreach($json as $name => &$arr){
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$stmt = $db->query($query);
//now comes the trick, that you tell pdo to fecth them already as array
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($arr);
echo json_encode($json);
?>
Look at the first example here: http://php.net/manual/de/pdostatement.fetchall.php
Also note the & before $arr, which will handle the $arr variable as reference (also the unset, because after the last pass, it would still be set, this is just good style to clean up)
Update:
As in the other answer you have to use PDO::FETCH_ASSOC to get an array with only the index names.
There are more than one error in your code:
$arDaniel = array();
$arAndi = array();
$arDave = array();
$arSimon = array();
for ($j=0; $j < 4; $j++) {
$name; # <---
$arr; # <---
This sort of ‘declaration’ in php is unnecessary, you can remove $name and $arr (it's not an error, btw);
if (j == 0) { # <---
In the for loop you use $j, you can't use j here: replace it with $j (in php variables are ever prepended by $);
$name = 'Daniel';
$arr = $arDaniel; # <---
By this assignment, you want change the original array, but with this assignment by value, you in fact create a copy of $arDaniel, and new elements are added only to $arr, not to $arDaniel; to do this, you have to do an assignment by reference through & keyword: replace this (and following similar) line with $arr = &$arDaniel;
}
elseif (j == 1) { # <--- see above
$name = 'Andi';
$arr = $arAndi; # <--- see above
}
elseif (j == 2) { # <--- see above
$name = 'Dave';
$arr = $arDave; # <--- see above
}
elseif (j == 3) { # <--- see above
$name = 'Simon';
$arr = $arSimon; # <--- see above
}
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $name ORDER BY date(Datum)";
$i = 1; # <---
The query is formally correct, but I don't know your table structure. $i = 1; is unnecessary (see below);
foreach($res = $db->query($query) as $value) {
$curr = array();
array_push($curr["Datum"] = $value[0]); # <---
array_push($curr["ID"] = $value[1]); # <---
array_push($curr["RR"] = $value[2]); # <---
array_push($curr["RL"] = $value[3]); # <---
array_push($curr["KB"] = $value[4]); # <---
array_push($curr["BD"] = $value[5]); # <---
array_push($curr["SD"] = $value[6]); # <---
array_push($curr["KH"] = $value[7]); # <---
array_push($curr["Reihenfolge"] = $value[8]); # <---
array_push($arr[$i] = $curr); # <---
$i++; # <---
}
}
The array_push syntax is not correct (see manual page): the correct syntax is array_push( $existentArray, $newElement ). In addition, you can't use array_push to add an associative value, you can use it only for numeric key. Change $curr assignments simply in $curr['Datum'] = $value[0]; etc...
To append $curr to $arr, you have to change the line in array_push( $arr, $curr ) or (better, as php recommends if only one element is appended) $arr[] = $curr;. After these changes, the $i++; line can be deleted.
$json = array(
"Daniel" => $arDaniel,
"Andi" => $arAndi,
"Dave" => $arDave,
"Simon" => $arSimon
);
echo json_encode($json);
$db = NULL;
Now your script is clean (I hope).
Your script remain a bit redundant. You can simplify it in this way:
$array = array( 'Daniel'=>array(), 'Andi'=>array(), 'Dave'=>array(), 'Simon'=>array() );
foreach( $array as $key => &$val )
{
$query = "SELECT Datum, ID, RR, RL, KB, BD, SD, KH, Reihenfolge FROM $key ORDER BY date(Datum)";
$result = $db->query( $query );
$val = $result->fetchAll( PDO::FETCH_ASSOC );
}
$json = json_encode( $array );
echo $json;
By this way, you init an array with names as key, then, in a foreach loop by reference (&$val) you perform a sql query searching in table $key and you fetch all results directly in array (in this example the values are stored as associative arrays, like in your example, but you can use PDO::FETCH_OBJ to store data as object). At the end, you encode the array end echo it.
Edit:
I see a previous answer nearly identical to mine...
BTW, I leave mine because I have spent a lot of time to explain various errors...

PHP min not working correctly

I have an array with 3 values(56.767, 360.997, 579.728). These are in an array($distance).
Well, when I run the min($distance) I get '360.997'. What gives?
<?php
include('mysql_connect.php');
$MasterState = 'CA';
$query = 'select * from estes_term where Dest_State = "'.$MasterState.'"';
$result = mysql_query($query);
if($result) {
$row = #mysqli_fetch_row($result);
}
$Term_Zip = array();
$Distance = array();
$i = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$Term_Zip[] = $row['Term_Zip'];
$Distance_xml = file_get_contents('http://zipcodedistanceapi.redline13.com/rest/ua6z0ep0djB3zHGz5Z40hONMVc8yuXgY8nx8BX8OhKSRrzqxzvyRjmDeyMM3J32S/distance.xml/90077/'.$Term_Zip[$i].'/mile');
$Distance[] = $Distance_xml;
$i++;
}
echo '<pre>';
var_dump($Term_Zip);
var_dump($Distance).'<br />';
$test1 = min($Distance);
$test = (array_keys($Distance, min($Distance)));
echo '<br />';
echo 'Min'.min($Distance);
?>
As #Rocket pointed out, your variables are stored as strings, not floats. This, the character "3" is smaller than "5", so it's the first one. To avoid this use Type Juggling or floatval() in your code to assure your vars are float as:
$Distance[] = floatval(trim($Distance_xml));
Do like this... We are converting all the array elements to float using array_map and then finding the min value from it.
<?php
$arr= array(56.767, 360.997, 579.728);
echo min(array_map('floatval',$arr));
OUTPUT :
56.767
EDIT :
To get the key , you can make use of array_search()
$key = array_search(min(array_map('floatval',$arr)), $arr);

Create new variable to store each result during While loop

I have a while loop that loops through 3 results and echo's these out in a list. It will always be 3 results.
Here is my current PHP:
while($row = sqlsrv_fetch_array($res))
{
echo "<li>".$row['SessionValue']."</li>";
// prefer to store each value in its own variable
}
However I'd like to store the $row['SessionValue'] value in each loop in a new variable.
So....
first loop: $i0 = $row['SessionValue'];
second loop: $i1 = $row['SessionValue'];
third loop: $i2 = $row['SessionValue'];
How would I achieve this with PHP?
Many thanks for any pointers.
$lst_count = array();
while($row = sqlsrv_fetch_array($res))
$lst_count[] = $row["SessionValue"];
You just need another variable that gets incremented:
$count = 0;
while($row = sqlsrv_fetch_array($res))
{
${i.$count++} = $row['SessionValue'];
}
You can do this have SUM of all value:
$total = array();
while($row = sqlsrv_fetch_array($res))
{
$total[] = $row["SessionValue"]
} $sumAll = array_sum($total);

php string name as variable

$string = "id";
want result to be like
$id = "new value";
How do I code this in php?
Edit..
How about the below?
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "3";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
Theres 2 main methods
The first is the double $ (Variable Variable) like so
$var = "hello";
$$var = "world";
echo $hello; //world
//You can even add more Dollar Signs
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
//... and so on ...//
#source
And the second method is to use the {} lik so
$var = "hello";
${$var} = "world";
echo $hello;
You can also do:
${"this is a test"} = "works";
echo ${"this is a test"}; //Works
I had a play about with this on streamline objects a few weeks back and got some interesting results
$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};
You are looking for Variable Variables
$$string = "new value";
will let you call
echo $id; // new value
Later in your script
Second answer in response to your edit:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
$id = array();
$name = array();
$value = array();
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
$id[$i] = $row['id'];
$name[$i] = $row['name'];
$value[$i] = $row['value'];
$i++;
}
}
This loops around your result, using the counter $i as the key for your result arrays.
EDIT
Additional answer in response to your comment:
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
This code creates a temporary multidimensional array to hold the column names and values the loops around that array to create your variable variable arrays. As a side not I had to use the temp array as $$column_name[$i] doesn't work, I would love to see alternative answers to this problem.
Final note #Paisal, I see you have never accepted an answer, I wouldn't have put this much effort in if I had seen that before!
You can do this
$$string = "new value";
juste double $
Are you referring to variable variables?
That would accomplish something like this:
$string = "id";
$$string = "new value";
This produces a variable $id with the value "new value".
Don't do that. Just use an array.
$arr[$string] = 'new value';
ref: How do I build a dynamic variable with PHP?
Try this :
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$i = 0;
if ($num_rows) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row AS $key => $value) {
${$key}[$i] = $value;
}
$i++;
}
}
For those of us who need things explained in great detail...
// Creates a variable named '$String_Variable' and fills it with the string value 'id'
$String_Variable = 'id';
// Converts the string contents of '$String_Variable', which is 'id',
// to the variable '$id', and fills it with the string 'TEST'
$$String_Variable = 'TEST';
// Outputs: TEST
echo $id;
// Now you have created a variable named '$id' from the string of '$String_Variable'
// Essentially: $id = 'Test';

Categories