Super simple

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
z3r0
Forum Newbie
Posts: 2
Joined: Thu Feb 18, 2010 10:41 am

Super simple

Post by z3r0 »

Or so I thought!

I'm trying to iterate through an array and test if any of the values are NULL or ""

and if they are I just want to insert XXX

I've tried many things and I'm so confused I'd appreciate any help at all.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Super simple

Post by pickle »

Code: Select all

foreach($yourArray as $key=>$value)
{
  if(is_null($value) or $value === '')
    $yourArray[$key] = 'XXX';
}
foreach() makes a new copy of the array before it iterates, so you can't just overwrite $value, you have to explicitly state what you want to change in the original array.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Super simple

Post by John Cartwright »

If you also want to consider 0, false and empty arrays as "empty", then you can replace

Code: Select all

if(is_null($value) or $value === '')
with

Code: Select all

if(empty($value))
z3r0
Forum Newbie
Posts: 2
Joined: Thu Feb 18, 2010 10:41 am

Re: Super simple

Post by z3r0 »

I really appreciate the help thanks when I try and run this it gives me

"Fatal error: Can't use function return value in write context in C:\xampp\htdocs\madlib.php on line 36"

For you though that would be line 4 I think it's the line with "$ yourArray[$key] = 'XXX';"

Again it looks like it should work to me and I guess that's why I'm so frustrated.
I TAKE IT BACK! I should have copied and pasted I was doing "$ yourArray($key) = 'XXX';"

instead of "$ yourArray[$key] = 'XXX';" which does work so thank you.
Post Reply