php - make a single dimensional array multidimensional

I have a function that loops through an array and runs database operations within each loop.
function myfunc($array) {
foreach($array as $a) {
// db operations here
echo $a["one"].'<br />';
echo $a["two"].'<br />';
}
}
but then sometimes, I have a single-dimensional array such as
$x = array(
'one' => '1',
'two' => '2'
);
myfunc($x);
however, it's falling to loop because there is nothing to loop over.
I get errors saying:
Warning: Illegal string offset 'one'
Warning: Illegal string offset 'two'
i know I could make the single dimensional array$x[]
but that would mean I have to reset it to empty each time ($x = array();
) - which isn't a problem but if it;s possible to loop over a single dimensional array, i'd rather do that
Answer
Solution:
If you know you have only one entry, you'll want to wrap it into a array of one, like this:
myfunc([$array]);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.