Jump to content

Archived

This topic is now archived and is closed to further replies.

seanlim

unset by assigning value?

Recommended Posts

Hi all,

Just need some help with the handling of an array.

My code is something like that after simplifying it quite abit.

[code]<?
function getValue($str){
if($str == "Value 2") return ""; // how to unset variable?
else return $str." - Test String";
}

$arrayname = array();
$arrayname[] = getValue("Value 1");
$arrayname[] = getValue("Value 2");
$arrayname[] = getValue("Value 3");

print_r($arrayname);
?>[/code]

The problem is in the 3rd line 'return "";'.

I want to be able to unset the value when getValue("Value 2") is called. I have tried returning NULL, ""[blank], false.. all doesn't (and shouldn't, in the first place) work.

In other words, what i get now is
[code]Array
(
    [0] => Value 1 - Test String
    [1] =>
    [2] => Value 3 - Test String
)[/code]

what i want is
[code]Array
(
    [0] => Value 1 - Test String
    [1] => Value 3 - Test String
)[/code]

Is this possible at all? the function unset would be able to do this, but i can't think of any way to insert the unset function here.

Any help would be much appreciated.

Share this post


Link to post
Share on other sites
What you want to do cannot be done in one function. Also, when unsetting an element in an array, the indices are not compressed as this example shows:
[code]<?php
$test = array(0,1,2,3,4,5,6,7,8);
echo '<pre> Before unset: ' . print_r($test,true) . '</pre>';
unset($test[4]);
echo '<pre> After   unset: ' . print_r($test,true) . '</pre>';
?>[/code]

Here's how I would solve your problem:
[code]<?php
function getValue($str){
if($str == "Value 2") return false;
return $str." - Test String";
}

$arrayname = array();
$arrayname[] = getValue("Value 1");
$arrayname[] = getValue("Value 2");
$arrayname[] = getValue("Value 3");

echo '<pre> Before: ' . var_export($arrayname,true) . '</pre>';

$tmp = array();
foreach($arrayname as $v)
     if ($v !== false) $tmp[] = $v;

$arrayname = $tmp;

echo '<pre>  After: ' . var_export($arrayname,true) . '</pre>';
?>[/code]

The "!==" operator in the "if" statement is not a typo. It makes sure that the "if" will only succeed if the value is the boolean "false". It will not succeed if the value is a numeric zero.

Ken

Share this post


Link to post
Share on other sites
Ok, that's good. Your script work very well.

Come to think of it, its quite a simple solution, Just couldn't think of this solution somehow..

I changed the code slightly and the ending now looks like this

[code]while($pnt = array_search(false, $arrayname))
    unset($arrayname[$pnt]);
$arrayname = array_values($arrayname);[/code]

Its working fine now. Thanks alot kenrbnsn!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.