warning illegal string offset php - php

Hi I am currently having an error that says illegal string offset and i already searh here I just know that you get that warning if you are treating a string as if it is an array but I am certain that I am using it as an array can anybody help me thanks
$data2 = array('EquipmentName' => $this->input->post('txt_equipb'),
'EquipmentType' => $this->input->post('txt_equiptype'),
'RequirementID' => $id2);
foreach($data2 as $d) {
$data2s = array('EquipmentName' => $d['EquipmentName'],
'EquipmentType' => $d['EquipmentType'],
'RequirementID' => $d['RequirementID']);
}

You've misunderstand the meaning of foreach.(sigh)
Suggestions Provided:
just var_dump($d); before assignment of $data2s, and you'll know the result.
In the foreach, as you could see, each $d is only the value part of $data2, which means in every assignment of $data2s, there's no key as 'EquipmentName', only a simple string.

If you're just gonna loop once to set array values to a variable, you may just simply do it this way without using a foreach loop.
$data2 = array('EquipmentName' => $this->input->post('txt_equipb'),
'EquipmentType' => $this->input->post('txt_equiptype'),
'RequirementID' => $id2);
$data2s = $data2;
print_r( $data2s ); // check if has values

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

Unexpected output when using PDO Fetch

I'm hoping somebody knows what is going on with this. I've never seen anything like this before. I'm trying to re-key the results from an indexed array to a keyed array using the value of 'code' in the results as it is a unique key. This happens in both PHP 5.4.16 and PHP 7.0.10
The following code produces very strange output:
$stmt = $conn->prepare( $sql );
$stmt->execute( $params );
$key = 'code';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print "Value of $key is '{$row['code']}'\n";
$rows[ ($row['code']) ] = $row;
}
This produces the following output:
'alue of code is '1286
] => Array
(
[code] => 1286
[EmployeeID] =>
[Name] =>
)
Notice how the value of $row['code'] is printed to STDOUT after the single quotes and the V in Value is cut off. This causes my re-keyed array ($rows) to have no key value. I've re-keyed arrays from database results thousands of times before and never had a problem until I started using PDO. Anybody have any ideas?
I simplified the quoting by issuing:
print "Value of $key is '"."{$row[$key]}"."'\n";
which resulted in:
'alue of EmployeeCode is '1286
I am mystified why it's cutting off the 'V' in Value.
I can get similar output without using any database calls this way:
$row = [
'code' => "1286\r",
'EmployeeID' => '',
'Name' => ''
];
print "Value of $key is '{$row['code']}'\n";
$rows[ ($row['code']) ] = $row;
print_r($rows);
Output:
'alue of is '1286
Array
(
] => Array
(
[code] => 1286
[EmployeeID] =>
[Name] =>
)
)
The \r character causes the output cursor to jump to the start of the line, so the ' that's overwriting your 'V' character is actually the second single-quote you're printing.
Likewise, in the strange output of print_r(), the \r is jumping the output cursor to the start of the line, so the ] => Array is overwriting what came before it, which was [1286\r.
I suspect the data in your database contains literal \r characters.

Modify Current Value of Multidimensional Array

I have three arrays, say multiarray, valsarray, and otherarray. otherarray is a multidimensional array that supplies values to multiarray and valsarray, but besides that it is unimportant here. valsarray takes values from a subarray of each value in otherarray and multiarray takes straight values from otherarray, as demonstrated below:
foreach($otherarray as $other){
foreach($other as $sub){
$valsarray[] = $sub
}
$multiarray[] = array('Val1' => $other['Val1'], 'Val2' => $other['Val2']);
}
Now what I would like to do is append each key/value pair in valsarray to the current array entry of multiarray, to achieve a result similar to:
$multiarray = array('Val1' => $other['Val1'], 'Val2' => $other['Val2'],
'VALSARRAY_KEY1' => VALSARRAY_VALUE1, ..., 'VALSARRAY_KEYN' => VALSARRAY_VALUEN)
I have attempted to solve this using current in the following fashion:
foreach($valsarray as $key => $val){
current($multiarray)[$key] = $val;
}
But the multiarray remained unaltered. I may be misunderstanding how current works, or how to approach this problem, so any help or direction would be appreciated.
EDIT- EXAMPLE
otherarray = array(...prior array entries...,
array('Val1' => 'abc',
'Val2' => 'cde',
'Val3' => 'not important',
'Val4' => array(0 => 'subA', 1 => 'subB'),
...next array entries...);
BEFORE MERGE:
multiarray = array(...prior entries...,
array('Val1' => 'abc',
'Val2' => 'cde'));
valsarray = array(0 => 'subA', 1 => 'subB');
AFTER MERGE:
multiarray = array(...prior entries...,
array('Val1' => 'abc',
'Val2' => 'cde',
0 => 'subA',
1 => 'subB'));
So if multiarray was a regular array instead of a multidimensional one, I would do something like:
foreach($valsarray as $key => $val){
$multiarray[$key] = $val;
}
To achieve the end result.
I am not 100% sure what you are trying to accomplish a Minimal, Complete, and Verifiable example may help if I have misunderstood something.
It appears that the current() function does not work as you assume. (Or more specifically, the internal pointer.)
If you look at the example in the PHP documentation: Current(), you will see that for current($array) to change elements, you need to call next($array) or prev($array).
These function move the internal pointer of the array.
Note that in PHP 5, foreach loops use the internal pointer (and reset it when you start a loop), but in PHP 7, foreach loops do not use the internal pointer.
Anyway, here is my best guess at what could help you.
$valsarray_index = 0;
foreach ($otherarray as $other) {
$multiarray_value = array('Val1' => $other['Val1'], 'Val2' => $other['Val2']);
foreach ($other as $sub) {
$multiarray_value[$valsarray_index] = $sub;
// $multiarray_value["VALSARRAY_KEY" . $valsarray_index] = $sub;
$valsarray[] = $sub;
$valsarray_index += 1; // This stays in lockstep with the last index of $valsarray
}
$multiarray[] = $multiarray_value;
}
I am not exactly sure about what you want the final output to look like. If this produces incorrect information, then if would be helpful to provide some specific arrays for input and what you expect as output.

PHP - 2D Arrays - Looping through array keys and retrieving their values?

I have an array that outputs like this:
1 =>
array
'quantity' => string '2' (length=1)
'total' => string '187.90' (length=6)
2 =>
array
'quantity' => string '2' (length=1)
'total' => string '2,349.90' (length=8)
I would like to loop through each array keys and retrieve the set of 3 values relating to them, something like this (which doesnt work):
foreach( $orderItems as $obj=>$quantity=>$total)
{
echo $obj;
echo $quantity;
echo $total;
}
Would someone be able to give some advice on how I would accomplish this, or even a better way for me to be going about this task. Any information relating to this, including links to tutorials that may cover this, would be greatly appreciated. Thanks!!
foreach( $orderItems as $key => $obj)
{
echo $key;
echo $obj['quantity'];
echo $obj['total'];
}
Using the above.
You need to read the docs on forEach() a little more, since your syntax and understanding of it is somewhat incorrect.
$arr = array(
array('foo' => 'bar', 'foo2', 'bar2'),
array('foo' => 'bar', 'foo2', 'bar2'),
);
foreach($arr as $sub_array) {
echo $sub_array['foo'];
echo $sub_array['bar'];
}
forEach() iteratively passes each key of the array to a variable - in the above case, $sub_array (a suitable name, since your array contains sub-arrays). So within the loop body, it's that you need to interrogate.

PHP pass by reference issue - can't change type?

I have a weird phenomenon. I hope someone can explain to me what is happening there:
I want to create a filter. The origin is something like '-10' or '10-20' or '20+' (type string) and the result should be 'Under $10', ... as well as 'product_price < 10', ... for a sql command.
But storing the array back on the original string doesn't work. It just delivers '$Array' as result. Is it not possible to pass by reference and change the type?
Thanks for your knowledge!
foreach($filters as &$filter){
preg_match ('#^\-(\d+)$#ism', $filter, $match);
if ($match[1]){
$filter = array(
'Under $'.intval($match[1]),
'product_price < '.intval($match[1])
);
}
...
}
return $filtering;
}
P.S.: I am not looking for a solution, because I could change the origin string into array, or I could change the foreach in to a pass by value and create a new array with the arrays like $newFilter[] = ... I am only curious
You can change it's type. Proof by construction:
<?php
header('Content-type:text/plain');
$arr = array(
'1',
'2',
);
foreach ($arr as &$filter) {
$filter = array($filter);
}
print_r($arr);
?>
Prints:
Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
)
You should change your foreach into
foreach($filters as $index => $filter)
and update your filter by doing
$filters[$index] = array(...);
I believe the $filter variable created by the foreach() statement is a copy of the data in the array and not a reference to it.

Categories