0

I am a newbe so maybe stupid question.. I have a couple of variables:

$opleidingscode1            = rgar( $entry, '31'); //$Opleidingssoortcode
$opleidingscode2            = rgar( $entry, '32'); //$Opleidingssoortcode
$opleidingscode3            = rgar( $entry, '33'); //$Opleidingssoortcode
$opleidingscode4            = rgar( $entry, '34'); //$Opleidingssoortcode
$opleidingscode5            = rgar( $entry, '35'); //$Opleidingssoortcode

Then put them in an array:

 $array = array( $opleidingscode1,$opleidingscode2,$opleidingscode3,$opleidingscode4,$opleidingscode5 );

Because only one variable has a value, rest is empty, i want to return only the value. So now i have:

$arrlength = count($array);

$string = "";
for($x = 0; $x < $arrlength; $x++) {
$string = $array[$x];
break; }

But it only returns a value if the last variable of the array has a value ($opleidingscode5)

What am i doing wrong?

3 Answers 3

1

What you are doing here is a for-loop, that loops on each value of your array (you got that right), but it stores the last value of your table to your $string variable because that's what you asked it to do.

You may want to add a condition to your $string = $array[$x]; statement in order to check if its empty or not, since you said "Because only one variable has a value, rest is empty, i want to return only the value."

Sign up to request clarification or add additional context in comments.

Comments

1

You're not checking if there's a value in the string, you're just getting each value and returning the last one. You need an if statement in your loop.

for($x = 0; $x < $arrlength; $x++) {
    if($array[$x] != NULL){
        $string = $array[$x];
    }
}

Comments

0

Here's what I would do - first filter for empty and then shift first item from the returned result:

$array = array_filter($array, function($value) {
    return !empty($value);
});

$value = array_shift($array);

That is if you only want the first item's value - otherwise you will already have all items that have values associated in the $array after running it via array_filter.

1 Comment

function($value) { return !empty($value); } is the default behaviour of array_filter() ... you can safely omit that part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.