Viewed   85 times

I have an array:

$a = array('foo' => 'fooMe');

and I do:

print_r($a);

which prints:

Array ( [foo] => printme )

Is there a function, so when doing:

needed_function('    Array ( [foo] => printme )');

I will get the array array('foo' => 'fooMe'); back?

 Answers

4

I actually wrote a function that parses a "stringed array" into an actual array. Obviously, it's somewhat hacky and whatnot, but it works on my testcase. Here's a link to a functioning prototype at http://codepad.org/idlXdij3.

I'll post the code inline too, for those people that don't feel like clicking on the link:

<?php
     /**
      * @author ninetwozero
      */
?>
<?php
    //The array we begin with
    $start_array = array('foo' => 'bar', 'bar' => 'foo', 'foobar' => 'barfoo');

    //Convert the array to a string
    $array_string = print_r($start_array, true);

    //Get the new array
    $end_array = text_to_array($array_string);

    //Output the array!
    print_r($end_array);

    function text_to_array($str) {

        //Initialize arrays
        $keys = array();
        $values = array();
        $output = array();

        //Is it an array?
        if( substr($str, 0, 5) == 'Array' ) {

            //Let's parse it (hopefully it won't clash)
            $array_contents = substr($str, 7, -2);
            $array_contents = str_replace(array('[', ']', '=>'), array('#!#', '#?#', ''), $array_contents);
            $array_fields = explode("#!#", $array_contents);

            //For each array-field, we need to explode on the delimiters I've set and make it look funny.
            for($i = 0; $i < count($array_fields); $i++ ) {

                //First run is glitched, so let's pass on that one.
                if( $i != 0 ) {

                    $bits = explode('#?#', $array_fields[$i]);
                    if( $bits[0] != '' ) $output[$bits[0]] = $bits[1];

                }
            }

            //Return the output.
            return $output;

        } else {

            //Duh, not an array.
            echo 'The given parameter is not an array.';
            return null;
        }

    }
?>
Monday, December 12, 2022
2

Newer versions of PHP allow using array_map() with a function expression instead of a function name:

$arr2 = array_map(function($person) {
    return $person['name'];
}, $arr1);

But if you are using a PHP < 5.3, it is much easier to use a simple loop, since array_map() would require to define a (probably global) function for this simple operation.

$arr2 = array();

foreach ($arr1 as $person) {
    $arr2[] = $person['name'];
}

// $arr2 now contains all names
Wednesday, August 24, 2022
1
string[] myArray = (string[])myarrayList.ToArray(typeof(string));
Thursday, August 11, 2022
5

Short answer is because the Go Language Specification does not permit it.

Quoting from the Go Language Specification: Conversions:

A non-constant value x can be converted to type T in any of these cases:

  • x is assignable to T.
  • x's type and T have identical underlying types.
  • x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
  • x's type and T are both integer or floating point types.
  • x's type and T are both complex types.
  • x is an integer or a slice of bytes or runes and T is a string type.
  • x is a string and T is a slice of bytes or runes.

The specification only allows converting a slice of bytes or runes to string, but not an array of bytes.

Long answer

In Go arrays and slices are distinct types. The size of an array is part of the type.

Slices are much more general than arrays, and converting an array to a slice which represents the same series of values is very easy: arr[:] (and is also cheap, the result slice will share the array as its backing array, no reallocation or copying will be done).

Because of this, all functions and support are provided for slices and not for arrays.

Just image you want to create a simple function which takes a slice (with any length) of int numbers and returns the sum of the numbers. Something like this:

func sum(s []int) (sum int) {
    for _, v := range s {
        sum += v
    }
    return
}

If you would decide to use an array as the input, since the length is part of the type, you would limit the usability of your function, it could only take arrays of the same length:

func sum2(s [2]int) (sum int) {
    for _, v := range s {
        sum += v
    }
    return
}

You can call sum2() only with values of type [2]int but if you have an array of type [3]int, you can't because those 2 types are distinct! You also cannot call sum2() if you only have a slice of int's (you can't access the backing array of a slice). Meanwhile you can call your sum() function with all []int slices, and if you have an array, you can still use it by passing arr[:] to your sum() function.

Note:

Also note that converting a "random" slice of bytes to a string is most likely not what you want because a "random" slice of bytes may not be a valid UTF-8 byte sequence.

Instead use the encoding/hex package to convert the result to a hex string like this:

fmt.Println(hex.EncodeToString(b[:]))
Tuesday, October 25, 2022
5

You did not create an array. What you did was Command Substitution which would simply put the output of a command into a variable.

In order to create an array, say:

temp_list=( $(grep "[a-z]" failedfiles.txt) )

You might also want to refer to Guide on Arrays.

Tuesday, August 9, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :