I try foreach loop but it keeps giving me "Undefined offset 2".
I tried also isset then I got "Undefined offset 1"
My code:
foreach ($lineArrayResults as $lineArrayResultKey => $lineArrayResult)
{
$currentFormFieldId = $submittedFormFields[$lineArrayResultKey]; // this line gives me error.
if($currentFormFieldId > 0)
{
$newLeadDataArray[$currentFormFieldId] = [
'field_name' => $formFields[$currentFormFieldId],
'field_value' => $lineArrayResult
];
}
}
the error undefined offset means that an array have ran out of bounds. the array size is smaller than the index that you are trying to fetch an object from.
First of all make sure your $submittedFormFields array contains the key of $lineArrayResultKey variable, if the array key is dynamically generated then try this code
foreach ($lineArrayResults as $lineArrayResultKey => $lineArrayResult)
{
if(!array_key_exists($lineArrayResultKey, $submittedFormFields)){
continue;
}
$currentFormFieldId = $submittedFormFields[$lineArrayResultKey];
if($currentFormFieldId > 0)
{
$newLeadDataArray[$currentFormFieldId] = [
'field_name' => $formFields[$currentFormFieldId],
'field_value' => $lineArrayResult
];
}
}
add # before $
try this
foreach ($lineArrayResults as $lineArrayResultKey => $lineArrayResult)
{
$currentFormFieldId = #$submittedFormFields[$lineArrayResultKey]; // insert # before $
if($currentFormFieldId > 0)
{
$newLeadDataArray[$currentFormFieldId] = [
'field_name' => $formFields[$currentFormFieldId],
'field_value' => $lineArrayResult
];
}
}
Related
I have an multidimensional array like this:
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
I need to check if the value eyetyy exists in this array under the key downloadnaam
Then I need to find the index of this value and remove it from the array.
The expected result:
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"]
];
I tried this:
$index = array_search($download->name, array_column($downloadArray, 'downloadnaam'));
if ($index !== null)
{
unset($downloadArray[$index]);
die("found index: " . $index);
}
$download->name contains 'eyetyy'
$downloadArray is my array
But it always dies and doesn't show any index on screen.
Can anyone help me?
Try in this way:
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
$filter = "eyetyy";
// Search for index
$index = array_search($filter, array_column($downloadArray, "downloadnaam"));
if ($index !== false) {
// Delete
array_splice($downloadArray, $index, 1);
}
print_r($downloadArray);
die();
Output:
Array
(
[downloads1] Array
(
[downloadnaam] fdgssgsfg
)
)
I got it working using this code
$downloadArray = array_filter($downloadArray, function ($item) use ($download) {
return $item['downloadnaam'] != $download->name;
});
This way I don't need to find the index first.
Credits to #Cositanto
you can try this :
$downloadArray = [
"downloads1" => ["downloadnaam" => "fdgssgsfg"],
"downloads2" => ["downloadnaam" => "eyetyy"],
];
foreach ($downloadArray as $subKey => $subArray) {
if (\in_array($subArray['downloadnaam'], ['eyetyy'], true)) {
unset($downloadArray[$subKey]);
}
}
var_dump($downloadArray);
Regards,
I'm working on a PHP function and getting this error I don't understand...
print_r($my_array); will output
Array (
[0] => Array (
[field_id_41] =>
)
)
but if I try to do
if ($my_array[0]['field_id_41'] == "some value")
I get the error
Undefined offset: 0
I've tried $my_array['0'] but that doesn't make a difference. I'm able to assign the value to another variable, and print that, but for some reason using it for the if statement breaks it.
I'm really not sure what's going on here... Any help appreciated.
EDIT: here's the actual loop I'm having trouble with
foreach($counsellors_result as $one_counsellor) {
$this_time_out_query = ee()->db->select('field_id_41')
->from('channel_data')
->where('entry_id', $one_counsellor['parent_id'])
->get();
$this_time_out = $this_time_out_query->result_array();
$time_out_status = $this_time_out['0']['field_id_41'];
if ($time_out_status != "Time Out") {
ee()->db->insert(
'relationships',
array(
'parent_id' => $entry_id,
'child_id' => $one_counsellor['parent_id'],
'field_id' => 111
)
);
}
}
try this way its help full
<?php
$this_time_out=array (0 => array ( 'field_id_41' =>""));
$time_out_status = $this_time_out[0]['field_id_41'];
if($time_out_status != ""){
echo $time_out_status;
}else{
echo "no any value<br><br>";
}
//print "no any value"
$this_time_out=array (0 => array ( 'field_id_41' =>"test"));
$time_out_status = $this_time_out[0]['field_id_41'];
if($time_out_status != ""){
echo $time_out_status;
}else{
echo "no any value";
}
//print "test"
Did you var_dump in every loop iteration? I can guess that you get array(array('field_id_41'=>'')) in the first iteration but null in the second iteration. When you look at the output you can't see var_dump(null).
Please try to dump it that way:
$i = 0;
foreach (...) {
//...
var_dump(array('i' => $i, 'var' => $time_out_status));
$i++;
//...
}
You'll probably see that in the second iteration you get:
array('i' => 1, 'var' => null)
seem to be experiencing something strange. I am loading an Excel file's data into an array. I am handling things like so
foreach ($data->toArray() as $value) {
dd($value);
if(!empty($value)){
foreach ($value as $v) {
dd($v['id']);
$insert[] = [
'id' => $v['id'],
'name' => $v['name']
];
}
}
}
Now the first dd() (laravel output) produces something like so
array:809 [▼
0 => array:20 [▼
"id" => "123"
"name" => "something"
]
...
So I can see there is an array element called id. The second dd, which calls this array element, produces the output 123
The problem comes where I am filling the array with this data. Although I am still using $v['id'] which works for the output, within the array I get the error
Undefined index: id
Why would this be the case when the index is there?
Thanks
Try to add an if to check if the keys really exist in your array. This will avoid situations when the key does not exist and the Undefined index: id error appear.
foreach ($data->toArray() as $value) {
if(!empty($value)){
foreach ($value as $v) {
if (array_key_exists("id",$v) &&
array_key_exists("name",$v)) {
$insert[] = [
'id' => $v['id'],
'name' => $v['name']
];
}
}
}
}
I've just got an unexpected result for a simple function which has an argument passed by reference.
Let's presume we have the following arrays:
$arr = array(
'Test' => 1,
'OtherKey' => 2,
);
$keyTranslation = array(
'OtherKey' => 'other_key',
'Test' => 'test',
);
The $keyTranslation array might not have the keys defined in the same order as the $arr. This is just to explain the need of the function.
and the following function:
function test(&$arr, $keyTranslation) {
foreach ($arr as $key => $value) {
$arr[$keyTranslation[$key]] = $value;
unset($arr[$key]);
}
}
The unexpected result is when simply call the function having the arrays above as arguments:
test($arr, $keyTranslation);
What I was expected?
array(2) {
["test"]=>
int(1)
["other_key"]=>
int(2)
}
What I've got?
NOTICE Undefined index: test on line number 10
NOTICE Undefined index: other_key on line number 10
NOTICE Undefined index: on line number 10
array(0) { }
Why was this happened?
Because each time I am adding a new value to the passed by reference array, the loop is iterating also over that value and unset it.
The question
Is this normal? or it is a bug in PHP?
This is what I would use as it seems a bit dodgy to be setting & unsetting elements of an array while foreaching through it...
function test(&$arr, $keyTranslation) {
$newarr = array();
foreach ($arr as $key => $value) {
$newarr[$keyTranslation[$key]] = $value;
}
$arr = $newarr; // Not sure if you'd have to unset $arr first...
}
Make sure you test if the translated key exists :
<?php
$arr = [ 'Foo' => 1, 'Bar' => 2 , 'dont_change' => 3, ];
$trans = [ 'Foo' => 'bar', 'Bar' => 'foo', 'Foobar' => 'foobar', ];
function test(&$arr, $trans) {
foreach($arr as $key => $value) {
if (!isset($trans[$key])) continue;
$arr[$trans[$key]] = $value;
unset($arr[$key]);
}
}
test($arr, $trans);
print_r($arr);
No Bug here. First of all the keys in $arr are 'Test' and 'OtherKey'. In your function you try to access $arr['test'] and $arr['other_key'], which do not exist, hence the notices. Then you unset the key and therefore the result is that $arr is null after the function call, as you passed $arr by reference.
If I have this array,
ini_set('display_errors', true);
error_reporting(E_ALL);
$arr = array(
'id' => 1234,
'name' => 'Jack',
'email' => 'jack#example.com',
'city' => array(
'id' => 55,
'name' => 'Los Angeles',
'country' => array(
'id' => 77,
'name' => 'USA',
),
),
);
I can get the country name with
$name = $arr['city']['country']['name'];
But if the country array doesn't exist, PHP will generate warning:
Notice: Undefined index ... on line xxx
Sure I can do the test first:
if (isset($arr['city']['country']['name'])) {
$name = $arr['city']['country']['name'];
} else {
$name = ''; // or set to default value;
}
But that is inefficient. What is the best way to get $arr['city']['country']['name']
without generating PHP Notice if it doesn't exist?
I borrowed the code below from Kohana. It will return the element of multidimensional array or NULL (or any default value chosen) if the key doesn't exist.
function _arr($arr, $path, $default = NULL)
{
if (!is_array($arr))
return $default;
$cursor = $arr;
$keys = explode('.', $path);
foreach ($keys as $key) {
if (isset($cursor[$key])) {
$cursor = $cursor[$key];
} else {
return $default;
}
}
return $cursor;
}
Given the input array above, access its elements with:
echo _arr($arr, 'id'); // 1234
echo _arr($arr, 'city.country.name'); // USA
echo _arr($arr, 'city.name'); // Los Angeles
echo _arr($arr, 'city.zip', 'not set'); // not set
The # error control operator suppresses any errors generated by an expression, including invalid array keys.
$name = #$arr['city']['country']['name'];