Php: Array returning empty - php

I am stumped on my array is not being saved after having values added to it in the functions. I believe it is a problem with the variables not being in the scope of the function. I have the following variables:
$oldInterestIdArray = array();
$newInterestsIdArray = array();
and I have some functions to populate the arrays:
function oldInterestIds($value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$oldInterestIdArray[] = $id;
}
function getNewInterestIds($value,$key)
{
if(interestExists($value))
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$newInterestsIdArray[] = $id;
}
else
{
addInterest($value);
$data = fetchInterestDetail($value);
$id = $data['id'];
$newInterestsIdArray[] = $id;
}
}
if(count($errors) == 0)
{
$newInterests = array_diff($interestsArray, $interests);
$common = array_intersect($interestsArray, $interests);
$toChangeId = array_diff($interests, $common);
array_walk($toChangeId, "oldInterestIds");
array_walk($newInterests, "getNewInterestIds");
echo json_encode($oldInterestIdArray);
}
}
But the $oldInterestIdArray is returning blank. But if I were to echo json inside the oldInterestIds function it works, which leaves me to believe this is a problem with the variables scope. I have tried changing the variable to:
global $oldInterestIdArray;
global $newInterestsIdArray;
But that is returning null. Any suggestions?

declare global $oldInterestIdArray; inside the function like
function oldInterestIds($value, $key)
{
global $oldInterestIdArray; // set here global;
$data = fetchInterestDetail($value);
$id = $data['id'];
$oldInterestIdArray[] = $id;
}
See Example

Pass your array in as a reference :
function oldInterestIds(&$arr, $value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$arr[] = $id;
}

Related

use variable inside function within function

i am trying to access $managers variable in change function.
public function ManagerPerDay() {
$query = $this->mysqli()->query('SELECT
manager,
count(manager) AS count
FROM
DATA
GROUP BY
manager
ORDER BY
count DESC');
$data = $query->fetch_all();
$managers = $this->GetManagers();
function Change($n)
{
$name = $managers[array_search($n[0], array_column($managers, 'id'))]['name'];
$n[0] = $name;
return $n;
}
$data = array_map('Change', $data);
array_unshift($data, ['Manager', 'Per Day']);
return $data;
}
i have tried global $managers; in change function but it also does not work.
Use array_walk which allows you to add your parameters
function Change(&$n, $key, $managers)
{
$name = $managers[array_search($n[0], array_column($managers, 'id'))]['name'];
$n[0] = $name;
}
array_walk($data, 'Change', $managers);
You could use the use keyword to pass that variable to the function. Something like this for example:
$data = array_map(function($n) use ($manager) {
$name = $managers[array_search($n[0], array_column($managers, 'id'))]['name'];
$n[0] = $name;
return $n;
}, $data);

copy dynamic value to array in php

Can we copy all the dynamic values to array for eg:
I have a function like this
<?php
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
addText($a,$b,$c)
{
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
I will pass different values to addText() function after that I have to access those inserted value using foreach from another function.
How can we do that .
Just define your php variable as global.
Eg. global $list_a,$list_b,$list_c;
When you are using that variable in any function then first declare above variables in that function.
Eg:
addText($a,$b,$c)
{
global $list_a,$list_b,$list_c;
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
To accomplish this you have to use concept of global variable
Try this:
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
function addText($a,$b,$c)
{
global $list_a, $list_b, $list_c;
array_push($list_a,$a);
array_push($list_b,$b);
array_push($list_c,$c);
}
addText('12','23',12);
echo '<pre>';
print_r($list_a);
print_r($list_b);
print_r($list_c);
This would work but it is bad design. See here why.
<?php
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
function addText($a,$b,$c)
{
global $list_a, $list_b, $list_c;
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
function foreachThem()
{
global $list_a, $list_b, $list_c;
foreach($list_a as $item)
{
//...
}
foreach($list_b as $item)
{
//...
}
foreach($list_c as $item)
{
//...
}
}
A better way would be saving them in a parent array (this is optional but it reduces the amount of parameters and therefor the amount of code) and passing it as reference. See here for info on passing by reference.
<?php
$theLists = array(
"a" => array(),
"b" => array(),
"c" => array()
);
// note the '&'
function addText(&$lists, $a,$b,$c)
{
$lists["a"][] = $a;
$lists["b"][] = $b;
$lists["c"][] = $c;
}
// '&' is not needed here
function foreachThem($lists)
{
foreach($lists["a"] as $item)
{
//...
}
foreach($lists["b"] as $item)
{
//...
}
foreach($lists["c"] as $item)
{
//...
}
}
Try this,
<?php
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
addText($a,$b,$c)
{
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
public function 'function_name'($list_a, $list_b, $list_c) {
foreach ($list_a as $list) {
echo $list;
}
}

PHP function not returning correctly

So basically I have an array, and I have a function that will return an array value, but it is not returning anything.
$skills = array("Attack");
$i = 0;
$hs = file_get_contents("localhost/player=".$_GET["player"]);
foreach($skills as $value) {
$hs[$i] = explode(",",$hs[$i]);
$stats[$value]["rank"] = $hs[$i][0];
$stats[$value]["level"] = $hs[$i][1];
$stats[$value]["xp"] = $hs[$i][2];
$i++;
}
function getSkill($skill) {
//echo $skill;
return $stats[$skill]["level"];
}
I have tried getSkill("Attack"); and it doesn't work;
but if I do echo $stats["Attack"]["level"]; it works fine.
You don't pass the $stats array to your function so it can't know what is in it.
function getSkill($stats, $skill) {
//echo $skill;
return $stats[$skill]["level"];
}
and call it with getSkill($stats,"Attack");

I'm passing too many parameters

I'm passing a lot of parameters in a function
I want to know if its wrong what i am doing and if it is possible to put all those variables into an array and just call the array:
Here my function parameters:
function addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description)
My code to recognize all the variables.
if (isset($_POST['add_jo'])){
$job_category =$_POST['job_category'];
$description = $_POST['description'];
$job_name = $_POST['job_name'];
$logo = $_POST['logo'];
$status = $_POST['status'];
$localization = $_POST['localization'];
$job_type = $_POST['job_type'];
$contract_type = $_POST['contract_type'];
addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description);
}else{
$logo = NULL;
$job_category = NULL;
$job_name = NULL;
$status = NULL;
$localization = NULL;
$description = NULL;
$job_type = NULL;
$contract_type = NULL;
$check1 = NULL;
$check2 = NULL;
}
Is it possible to do something like this?
if(isset($_POST['mybutton'])){
array[](
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
);
function(callarrayhere);
else{
$var1 = null;
$var2 = null;
}
Thanks.
Since $_POST is already an array, just use it:
addjob($_POST);
And in addjob:
function addjob($input) {
// verify that array items are present and correct.
}
Exporting an array's values to individual variables is not only a waste of time and memory, but it also makes your code harder to read (where do these variables come from? It's not obvious they came from the same source array)
Of course it's possible:
if (isset($_POST['add_jo'])){
$a = array();
$a['job_category'] =$_POST['job_category'];
$a['description'] = $_POST['description'];
// and so on
$a['contract_type'] = $_POST['contract_type'];
addjo($a);
}
else
{
$a['job_category'] = null;
// and so on
}
And in function addjo you can display all values that way:
function addjo($a) {
foreach ($a as $k => $v) {
echo $k.' '.$v."<br />"
}
// or
echo $a['job_category'];
}
Yes it is possible to have an array as an argument to a function. Your syntax isn't quite right. This would do it:
function addjo($params){
echo $params['logo'];
echo $params['job_category'];
echo $params['job_name'];
}
Usage example:
$arr = array(
'logo' => $logo,
'job_category' => $job_category,
'job_name' => $job_name
);
addjo($arr);
You could also have default parameters for each of the array elements, or make them optional. See this answer for how to do that.

PHP: Undefined property stdClass, but the property is already exists

Below is my class.
class MaterialType {
public $id;
public $name;
function getAllMaterialType() {
$query = "SELECT * FROM material_types";
$result = mysql_query($query);
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = new MaterialType();
$arr[]->id = $row['m_type_id'];
$arr[]->name = $row['m_type_name'];
}
return $arr;
}
}
The problem is when I create object in an array like above, and display it using foreach,
there are errors that say Undefined property stdClass. I already defined the property that being used, so why these errors appear? Below is the code that I use to
display data.
$materialTypeObj = new MaterialType();
foreach($materialTypeObj->getAllMaterialType() as $mat) {
echo $mat->name;
}
Every time you do $array[] = it inserts a new element in the end of an array. What you need to do is:
class MaterialType {
public $id;
public $name;
function getAllMaterialType() {
$query = "SELECT * FROM material_types";
$result = mysql_query($query);
$arr = array();
while($row = mysql_fetch_array($result)) {
$mat = new MaterialType();
$mat->id = $row['m_type_id'];
$mat->name = $row['m_type_name'];
$arr[] = $mat;
}
return $arr;
}
}

Categories