• 14
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

delete all values from an array while keeping keys intact

Do I really have to do this to reset an array ??

foreach ($array as $i => $value) {
    unset($array[$i]);
}

EDIT:

this one makes more sense, as the previous one is equivalent to $array=array();

foreach ($array as $i => $value) {
    $array[$i]=NULL;
}
$keys = array_keys($array);
$values = array_fill(0, count($keys), null);
$new_array = array_combine($keys, $values);

Get the Keys

Get an array of nulls with the same number of elements

Combine them, using keys and the keys, and the nulls as the values

As comments suggest, this is easy as of PHP 5.2 with array_fill_keys

$new_array = array_fill_keys(array_keys($array), null);
  • 47
Reply Report

Define this function and call it whenever you need it:

function erase_val(&$myarr) {
    $myarr = array_map(create_function('$n', 'return null;'), $myarr);
}

// It's call by reference so you don't need to assign your array to a variable.
// Just call the function upon it
erase_val($array);

That's all!

  • 12
Reply Report
      • 1
    • I'm sorry, but this is by far the worst answer posted - create_function() is basically eval() and definitely should not be used to solve a problem as trivial as this one. Besides, a function for that is also completely overkill. IMO, this should not be the accepted answer.
    • @mindplay.dk This answer is just outdated. It was posted at a time were this was the most reliable way to achieve such things. Most webhosts were still on PHP v5.0 at that time. Let's call it a piece of history.

There is no build-in function to reset an array to just it's keys.

An alternative would be via a callback and array_map():

$array = array( 'a' => 'foo', 'b' => 'bar', 'c' => 'baz' );

With regular callback function

function nullify() {}
$array = array_map('nullify', $array);

Or with a lambda with PHP < 5.3

$array = array_map(create_function('', ''), $array);

Or with lambda as of PHP 5.3

$array = array_map(function() {}, $array);

In all cases var_dump($array); outputs:

array(3) {
  ["a"]=> NULL
  ["b"]=> NULL
  ["c"]=> NULL
}
  • 10
Reply Report
    • @stereofrog Right. I've changed the functions. Not that it is wrong with body and argument, but why add clutter... Thanks.

Flip the array to get the keys, then gives all keys the value NULL:

array_fill_keys(array_flip($array), NULL);

About array_fill_keys():

The array_fill_keys() function fills an array with values, specifying keys.

About array_flip():

The array_flip() function flips/exchanges all keys with their associated values in an array.

  • 4
Reply Report
foreach($a as &$v)
   $v = null;

The reasoning behind setting an array item to null is that an array needs to have a value for each key, otherwise a key makes no sense. That is why it is called a key - it is used to access a value. A null value seems like a reasonable choice here.

Wrap it in a [reusable] procedure:

function array_purge_values(&$a)
{
    foreach($a as &$v)
       $v = null;
}

Keep in mind though that PHP version starting from 5.3 pass values to functions by reference by default, i.e. the ampersand preceding argument variable in the function declaration is redundant. Not only that, but you will get a warning that the notion is deprecated.

  • 2
Reply Report
      • 2
    • @Gordon He could easily put this in a utility class and call it statically from there - no global scope pollution whatsoever. @amn Well, your code does the trick, for sure. But most likely the programmer won't comment on why he is doing the nullification EVERY time he needs to. So, implementing a reusable function and commenting what it is for (NOT what it does, that's obvious) is best practice. Besides that, it's more error prone as the programmer could have an error EVERY single time he writes that piece of code (unlikely here, but you grasp the concept).
      • 2
    • @aefx Yes. He could have done that. So could you in your answer. But you didn't. The point is: @amn gave a working solution to the problem at hand. He ockham'ly omitted everything not relevant for the solution. And you tell him his solution stinks. That's ridiculous. The OP didn't ask for reusability and used a foreach himself.
    • @aefxx Then just wrap it into a function and pollute the global scope with the smell of just another userland function
      • 1
    • aefxx, you are very welcome to explain why this stinks. This is not a review board, people usually do explain their arguments here. I have edited my post to include exactly what you perhaps felt was missing.

If you need to nullify the values of a associative array you can walk the whole array and make a callback to set values to null thus still having keys

array_walk($ar,function(&$item){$item = null;});

In case if you need to nullify the whole array just reassign it to empty one

$ar = array();
  • 1
Reply Report

I don't get the question quite well, but your example

foreach ($array as $i => $value) {
    unset($array[$i]);
}

is equivilent to

$array = array();
  • 0
Reply Report
    • Yes, that's true, The keys get deleted also... I wanted a built-in function to do this : foreach ($array as $i => $value) { $array[$i]=NULL; }

This is a fairly old topic, but since I referenced to it before coming up with my own solution for a more specific result, so therefore I will share with you that solution.

The desired result was to nullify all values, while keeping keys, and for it to recursively search the array for sub-arrays as well.

RECURSIVELY SET MULTI-LEVEL ARRAY VALUES TO NULL:

function nullifyArray(&$arrayData) {

  if (is_array($arrayData)) {
    foreach ($arrayData as $aKey => &$aValue) {
      if (is_array($aValue)) {
        nullifyArray($aValue);
      } else {
        $aValue = null;
      }
    }
    return true;     // $arrayData IS an array, and has been processed.
  } else {
    return false;    // $arrayData is NOT an array, no action(s) were performed.
  }

}

And here is it in use, along with BEFORE and AFTER output of the array contents.

PHP code to create a multilevel-array, and call the nullifyArray() function:

// Create a multi-level array.
$testArray = array(
    'rootKey1'              =>  'rootValue1',
    'rootKey2'              =>  'rootValue2',
    'rootArray1'            =>  array(
        'subKey1'           =>  'subValue1',
        'subArray1'         =>  array(
            'subSubKey1'    =>  'subSubValue1',
            'subSubKey2'    =>  'subSubValue2'
        )
    )
);

// Nullify the values.
nullifyArray($testArray); 

BEFORE CALL TO nullifyArray():

Array
(
    [rootKey1] => rootValue1
    [rootKey2] => rootValue2
    [rootArray1] => Array
        (
            [subKey1] => subValue1
            [subArray1] => Array
                (
                    [subSubKey1] => subSubValue1
                    [subSubKey2] => subSubValue2
                )

        )

)

AFTER CALL TO nullifyArray():

Array
(
    [rootKey1] => 
    [rootKey2] => 
    [rootArray1] => Array
        (
            [subKey1] => 
            [subArray1] => Array
                (
                    [subSubKey1] => 
                    [subSubKey2] => 
                )

        )

)

I hope it helps someone/anyone, and Thank You to all who previously answered the question.

  • 0
Reply Report

Just do this:

$arrayWithKeysOnly = array_keys($array);

http://php.net/manual/en/function.array-keys.php

EDIT: Addressing comment:

Ok, then do this:

$arrayWithKeysProper = array_flip(array_keys($array));

http://www.php.net/manual/en/function.array-flip.php

EDIT: Actually thinking about it, that probably won't work either.

  • -1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions