Welcome Guest, Not a member yet? Register   Sign In
WHY do PHP reindex arrays and add integer indexes?
#1

OK, SOMEONE please explain to me me WHY, when passing serialized data from the client to the server, does PHP reindex it all and add integer indexes to my array? Leave it alone, God Dammit!

HOW do I use PHP arrays in a 'normal' way (have them NOT act as associative arrays or ordered maps)?

I want a bleedin' list of items, and NOT having them prefixed with indexes – they're an index by themselves, dammit!

Needed to get this out, as I've spent the WHOLE BLOODY day fucking around with this ...
Reply
#2

ALL PHP ARRAYS are associative arrays.

So your simple single dimensional array of : 
PHP Code:
$myArray = ['apple''banana''cherry']; 

is structurally the same as: 
PHP Code:
$yourArray = [=> 'apple'=> 'banana'=> 'cherry']; 

So, if you will using foreach like this:
PHP Code:
foreach ($myArray as $index => $value)
{
    echo 
$index ' ' $value;
}

// You'll get
// 0 apple
// 1 banana
// 2 cherry 

That's simply how PHP internals work. If you ask why is that, then you need to ask the PHP maintainers themselves.
Reply
#3

OK, like ALL other times, it isn't until I run into a forum and scream and kick in a post, that I find the answer (yes, I may have a theory on this ... for another post another day).

There's a HUGE difference in sending an array prepared by using .serializeArray() and sending it DIRECTLY (not as a property of an object) to CI4, and handle it using $request->getRawInput().

IF, on the other hand, you NEED to wrap it as part of an object – in order to be able to send more data along – you should change from form.serializeArray() to just form.serialize(). And then when getting the raw input on the server, you have to manually convert to array (using parse_str() or whatever you need to do).

To sum it all up: You should NOT use .serializeArray() on the form anymore, but .serialize() instead. And when using $request->getRawInput() with a JSON object from the client you HAVE TO MANUALLY use parse_str for nested arrays on that object.

Holy crap, what a day!
Reply
#4

(12-17-2020, 08:40 AM)blaasvaer Wrote: OK, like ALL other times, it isn't until I run into a forum and scream and kick in a post, that I find the answer (yes, I may have a theory on this ... for another post another day).

Maybe because that's super basic stuff and you are kind of rude in your post, people will not rush to explain that to you! Screaming and kicking is not the best approach to have a reply.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#5

Thank you for the comment.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB