PHP 8.0 - How to replace deprecated each() - with foreach()? [duplicate] - php

This question already has answers here:
How can I update code that uses the deprecated each() function?
(12 answers)
Closed last month.
I understand that the each function() is deprecated in PHP 8.0.
Updated: I'm getting a Fatal error: Uncaught Error: Call to undefined function each() line 742 - [line 742 is this line in the code snippet below: list($orig,$values) = each($where); ]
I am trying to replace it in the below code with foreach() as suggested in this post, but I am not experienced enough in PHP or coding to achieve this. Can anyone help?
public function getMetaboxConfig($type) {
static $cache;
if (!empty($cache[$type])) {
return $cache[$type];
}
do_action("pe_theme_metabox_config_$type");
$config =& PeGlobal::$config;
$metaboxes = PeGlobal::$config["metaboxes"];
$pmboxes = empty($config["metaboxes-$type"]) ? null : $config["metaboxes-$type"];
if ($custom = apply_filters("pe_theme_metabox_$type",$pmboxes)) {
//print_r(array_keys(PeGlobal::$config["metaboxes-view"]));
$keys = array_keys($custom);
foreach ( $custom as $key => $value ) {
$metaboxes[$key] = $custom[$key];
$where =& $metaboxes[$key]["where"];
list($orig,$values) = each($where);
if ($orig != $type) {
unset($where[$orig]);
$where[$type] = $values;
}
}
}
$cache[$type] = $metaboxes;
return $metaboxes;
}
The error I am seeing:
Error message

This is an exemple to foreach :
<?php
$myArr = [
'key1' => 'value1',
'key2' => 'value2',
];
foreach($myArr as $k => $v){
//first iteration : $k = 'key1', $v = 'value1'
//second iteration : $k = 'key2', $v = 'value2'
... your code
}
So, you don't need to use array_keys :
foreach ($custom as $key => $value) {
$metaboxes[$key] = $value;
...
}

Related

array to object throwing Uncaught Error: Call to undefined method stdClass

I am trying to reconstruct an object from code. First I explode the calls to the object into an array, and then convert the array into an object, and then test to see if the call works.
The object created seems fine, but the test call fails.
$claim = new_client();
print_r($claim);
$pat = $claim->patientFirstName();
echo $pat;
function new_client()
{
$text = '
$claim->patientFirstName()
UNWANTED STUFF.
$claim->patientMiddleName()
UNWANTED STUFF.....
$claim->patientLastName() ';
$client = array();
$i = 1 ;
$array = (explode("claim->",$text));
foreach ($array as &$variable) {
$variable = substr($variable, 0, strpos($variable, "()"));
$client[$variable] = $i;
$i++;
}
unset ($variable);
$object = new stdClass();
foreach ($client as $key => $value)
{
$object->$key = $value;
}
return $object;
}
Here is the result.
stdClass Object ( [] => 1 [patientFirstName] => 2 [patientMiddleName] => 3
[patientLastName] => 4 )
Fatal error: Uncaught Error: Call to undefined method
stdClass::patientFirstName()...
So any ideas as to why
$pat = $claim->patientFirstName();
is failing?
You are accessing the element is a wrong way.
$claim->patientFirstName
$claim->patientMiddleName

Error while using Error of error in PHP

I want to do the same actions thru some variables. So I created the variables of variables. But it is throwing me error - "Invalid argument supplied for foreach()" when I am looping thru $$a. I have check the type of the variable. It is array. Then what is the error ?
$edu_data = Json::decode($model->education);
$exp_data = Json::decode($model->experience);
$avail_data = Json::decode($model->availability);
$docs_data = Json::decode($model->documents);
$model_edu = new \admin\models\ApplicantEducation();
$model_exp = new \admin\models\ApplicantExperience();
$model_avail = new \admin\models\Availability();
$model_cre = new \admin\models\Credential();
$all = array('edu_data' => 'model_edu', 'exp_data' => 'model_exp', 'avail_data' => 'model_avail', 'docs_data' => 'model_cre');
foreach ($all as $a => $s)
{
$arr = $$a;
foreach ($arr as $v)
{
$$s->applicant_id = $applicant_id;
foreach ($arr[1] as $k1 => $v1)
{
$$s->$k1 = $v[$k1];
}
$$s->save();
}
}
Your array does not contain your variables (e.g. $model_edu), but only their respective names as string values ('model_edu'). Edit: My bad, I didn't notice this is intentional.
I suggest using a function:
function process_data($model, $data, $applicant_id) {
foreach ($data as $v) {
$model->applicant_id = $applicant_id;
foreach ($data[1] as $k1 => $v1)
{
$model->$k1 = $v[$k1];
}
$model->save();
}
}
process_data($model_edu, $edu_data);
process_data($model_exp, $exp_data);
process_data($model_avail, $avail_data);
process_data($model_docs, $docs_data);
Your code will be more easily comprehendable.
Apart from that, you can debug your code like this to find out exactly where and when the error happens:
foreach ($all as $a => $s)
{
$arr = $$a;
var_dump($arr);
foreach ($arr as $v)
{
$$s->applicant_id = $applicant_id;
var_dump($arr[1]);
foreach ($arr[1] as $k1 => $v1)
{
$$s->$k1 = $v[$k1];
}
$$s->save();
}
}
See if this is the expected value and proceed from there on.
Find out if the reason is an unexpected value in one of your variables or if it is an error in the code logic.

PHP Accessing Array Value [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
i am trying to access the value of an array that i have created, but it seems to fail.
I am looping through an array that sends VIA http, and adding the docno and entryno to new array called $ArrID, it can be added to the new array, however when i try to access the ArrID it seem to get nothing from the array itself while i am confident that ArrID contain the items
CODE
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value -> doc_no;
$entryno = $value -> entryno;
if($mysqli->query($sql) == 1){
$itemArr = array('docno' => $docno, 'entryno' => $entryno);
$ArrID[] = $itemArr;
}
}
if(count($ArrID)>0){
foreach ($ArrID as $key => $values) {
echo $values -> docno;
}
}
You are mixing with object and array
see http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/language.types.object.php
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value['doc_no'];
$entryno = $value['entryno'];
if($mysqli->query($sql) == 1){
$itemArr = array('docno' => $docno, 'entryno' => $entryno);
$ArrID[] = $itemArr;
}
}
if(count($ArrID)>0){
foreach ($ArrID as $key => $values) {
echo $values['docno'];
}
}
How are you sure that your array has the data? Make sure by echoing the size of the array and see if its greater then zero.
Try the code below and check if it works or not. There was a redundant assign and reassign code, actually you were assigning array to a variable, and variable to an array again.
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value -> doc_no;
$entryno = $value -> entryno;
if($mysqli->query($sql) == 1) {
$ArrID[] = array('docno' => $docno, 'entryno' => $entryno);
}
}
if(count($ArrID)>0) {
foreach ($ArrID as $key => $values) {
echo $values -> docno;
}
}

PHP Error Undefined Offset, SQL Export tool

I keep getting the error:
PHP Notice: Undefined offset: 1 in /home/mydomain/mydomain.com/admin/model/tool/export_xls.php on line 150
I've looked at the other similar posts but none of those resolutions work on my code. I don't see any numbers related to the array, and I've double checked for missing closing } . I asked the code developer and all he did was get it to stop displaying the error, but it still shows up (several thousand times) in my error log. line 150 is the blank line above the code
"//Get all options values to each option"
Code:
public function get_all_options()
{
$this->load->model('catalog/option');
$all_options = $this->model_catalog_option->getOptions();
$options_final = array();
//Format options
foreach ($all_options as $key => $op) {
$options_final[$op['name'].'_'.$op['type']] = array(
'option_id' => $op['option_id'],
'option_name' => $op['name'],
'option_values' => array()
);
}
//Get all options values to each option
foreach ($options_final as $option_name => $op) {
$option_values = $this->model_catalog_option->getOptionValues($op['option_id']);
//Format option values
$option_values_final = array();
foreach ($option_values as $key => $op) {
$option_values_final[$op['name']] = $op['option_value_id'];
}
$options_final[$option_name]['option_values'] = $option_values_final;
}
return $options_final;
}
This is because you are accessing an array which index is not set . try something like this
//Format options
foreach ($all_options as $key => $op) {
$options_final[$op['name'].'_'.$op['type']]
= array(
'option_id' =>isset($op['option_id']) ?
:$op['option_id']:null,
'option_name' => isset($op['option_name'])
? :$op['option_name']:null,
'option_values' => array()
);
}

Array to string conversion php, assoc array

I have a simple Template engine and I have a problem giving it a data from assoc array. Can anybody give me an advice? In method getStatisticData, I give an assoc array as first variable $data. My input array is in the form:
[0] => Array
(
[OrderNumber] => 1
[Name] => Zahid
[Total revenue] => 8363.38
)
I'm trying to get data from it using foreach but it doesn't work. I'm getting notice
Notice: Array to string conversion in C:\Server\htdocs\Task\lib\TemplateGen.php on line 34
protected function getStatisticData($data, $template){
$text = "";
if($data === false) {
return "We don't have any data in database";
}
foreach($data as $key => $value){
$data[$key] = $value;
$text .= $this->template_gen->getReplaceTemplate($data ,$template);
}
return $text;
}
getReplaceContent and associated methods from TemplateGen.php:
private function getReplaceContent($dataString, $content)
{
$search = array();
$replace = array();
$i = 0;
foreach ($dataString as $key => $value) {
$search[$i] = "%$key%";
$replace[$i] = $value;
$i++;
}
return str_replace($search, $replace, $content); ## LINE 34
}
function getReplaceTemplate($dataString, $template)
{
return $this->getReplaceContent($dataString, $this->getTemplate($template));
}
function getTemplate($name)
{
return $content = file_get_contents($this->config->tpl_path . $name . ".tpl");
}
UPDATE:
I got 2 new errors
Warning: implode(): Invalid arguments passed in C:\Server\htdocs\Task\lib\TemplateGen.php on line 28
Fatal error: Cannot redeclare add_percent() (previously declared in C:\Server\htdocs\Task\lib\TemplateGen.php:25) in C:\Server\htdocs\Task\lib\TemplateGen.php on line 25
Line 25:
function add_percent($i) {
Line 28:
return implode("", str_replace(array_map("add_percent", array_keys($dataString)), array_values($dataString),$content));
UPDATE2:
In theory, everything provided in new method should work very well. But there are same problems which were at the beginning
Notice: Array to string conversion in C:\Server\htdocs\Task\lib\TemplateGen.php on line 44`
line 44 :
return str_replace(
array_map($addPercent, array_keys($data)), array_values($data), $template
);
But if I'am using my getStatisticData instead of yours, it works but there are many other errors
My method :
protected function getStatisticData($data, $template){
$text = array();
if($data === false) {
return "We don't have any data in database";
}
$i=0;
foreach($data as $dataString){
if (!empty($data[$i+1])){
foreach($dataString as $key => $value){
$dataString[$i][$key] = $dataString[$i][$value];
}}
$text .= $this->template_gen->getReplaceTemplate($dataString ,$template);
}
return $text;
}
Your code is rather inefficient at present, and it's leading to some isuues. Let's look at the first method you posted:
protected function getStatisticData($data, $template){
$text = "";
if($data === false) {
return "We don't have any data in database";
}
foreach($data as $key => $value){
$data[$key] = $value;
$text .= $this->template_gen->getReplaceTemplate($data ,$template);
}
return $text;
}
The foreach loop is doing the same thing for each key/value pair (plus $data[$key] = $value is redundant as you are already getting each key and value in the foreach loop), so you could eliminate the loop, and replace it with something like this:
protected function getStatisticData($data, $template){
if ($data === false) {
return "We don't have any data in database";
}
return $this->template_gen->getReplaceTemplate($data, $template);
}
Similarly for getReplaceContent - you're basically using the array keys and array values as the search and the replacement values. You can use PHP's handy array_keys and array_values instead of building new arrays. The catch is that the array keys need to be surrounded by %, but that is easy to do using array_map - just define a function that will take in a string and add % to either end of it, and then array_map it to your array keys:
private function getReplaceContent($data, $template)
{
$addPercent = function( $i ){
return "%$i%";
};
return str_replace(
array_map( $addPercent, array_keys($data)), array_values($data), $template
);
}
Now, calling getStatisticData will return the template text with all the replaced data in it.
Sample input:
$arr = array(
'OrderNumber' => 1,
'Name' => 'Zahid',
'Total revenue' => '8363.38'
);
$template =
'<p>Name: %Name%<br>
Total revenue: %Total revenue%<br>
Order number: %OrderNumber%</p>';
Output of getStatisticData:
<p>Name: Zahid<br>
Total revenue: 8363.38<br>
Order number: 1</p>
EDIT: it is not clear from the OP what the input to getStatisticData is, but it looks like it is supposed to be an array of associative arrays. If this is so, the code for getStatisticData should be altered as follows:
protected function getStatisticData($dataArray, $template){
if ($dataArray === false) {
return "We don't have any data in database";
}
$text = "";
foreach ($dataArray as $aa) {
$text .= $this->template_gen->getReplaceTemplate($aa, $template);
}
return $text;
}
Sample input:
$arr =
[
[ 'OrderNumber' => 1,
'Name' => 'Zahid',
'Total revenue' => '8363.38'
],
[ 'OrderNumber' => 2,
'Name' => 'Paul',
'Total revenue' => '123.45'
],
[ 'OrderNumber' => 3,
'Name' => 'Jane',
'Total revenue' => '567.89'
],
];
Output:
<p>Name: Zahid<br>
Total revenue: 8363.38<br>
Order number: 1</p>
<p>Name: Paul<br>
Total revenue: 123.45<br>
Order number: 2</p>
<p>Name: Jane<br>
Total revenue: 567.89<br>
Order number: 3</p>
I'm assuming that the associative array $data has simply strings in it. I'm assuming that the $data array has its keys as the template placeholder and the value as the value to input.
If so, and if you're trying to get a single string, then consider doing this:
protected function getStatisticData($data, $template) {
if ($data === false) {
return "We don't have any data in the database.";
}
return this->template_gen->getReplaceTemplate($data, $template);
}
private function getReplaceContent($dataString, $content) {
content = '';
foreach ($dataString as $key => $value) {
$content .= str_replace("%{$key}%", $value, $content);
}
return $content;
}
You don't need quite as many foreach loops. One should do just fine.

Categories