Convert Array to String

Asked

Viewed 18,115 times

4

Why when I convert the array to a string it doesn’t convert all the keys of the right array:

Code:

<?php

        $bMsg3 = array(
            $at1 = 0,   /* Inteiro */
            $at2 = "",  /* String */
            $at3 = 0.0,  /* Float */
            $at4 = 0  /* Float */
        );

        $bMsg3[$at1] = 400;
        $bMsg3[$at2] = "Hello World!";
        $bMsg3[$at3] = 3.14;
        $bMsg3[$at4] = 200.0;


        // Converte para string
        $str = implode(':', $bMsg3);

        print "String: $str";

        ?>

The result is: String: 200::0:0:hello world!

Which should be: 400:Hello World!: 3.14:200.0

Does anyone know why?

4 answers

4

Do it like this =

    $bMsg3[] = 400;
    $bMsg3[] = "Hello World!";
    $bMsg3[] = 3.14;
    $bMsg3[] = 200.0; 

    // Converte para string
    $str = implode(':', $bMsg3);

    print "String: $str";
    ?>

Result = String: 400:Hello World!: 3.14:200

3

In php, the function implode does not work for keys, but only for the values of the array.

Example:

$array = ['site' => 'stackoverlow', 'linguagem' => 'portugues']

implode(',', $array); // string: stackoverflow, portugues

How to assign an array or group variables?

Now, the first part of your code seems to have an error, since you can’t assign like this:

$bMsg3 = array(
            $at1 = 0,   /* Inteiro */
            $at2 = "",  /* String */
            $at3 = 0.0,  /* Float */
            $at4 = 0  /* Float */
        );

But only so (with the =>):

$bMsg3 = array(
            $at1 => 0,   /* Inteiro */
            $at2 => "",  /* String */
            $at3 => 0.0,  /* Float */
            $at4 => 0  /* Float */
        );

Unless you wanted to do an assignment for the key values in bulk. Then it should look like this:

 $at1 = 0;
 $at2 = "";
 $at3 = 0.0;
 $at4 = 0;

Or so:

list($at1, $at2, $at3, $at4) = array(0, "", 0.0, 0);

Important remark!

In PHP, values accepted for arrays are only integers and strings. Values such as float are not accepted.

I saw it in the ZEND exam:

$array[1.0] = 1;
$array[1.1] = 1.1;

count($array); // retorna 1

Check out on IDEONE

What can be done is create a representation for the value float through a string.

Thus:

$array['0.0'] = 0;

2


The result is not as expected because you are doing multiple assignments in the same key.

Basicamento all variables have the value zero, except $at2. In assignments you pass the value of zero practice every time except $at2

    $bMsg3 = array($at1 = 0, $at2 = "", $at3 = 0.0, $at4 = 0);


    $bMsg3[$at1] = 400;
    $bMsg3[$at2] = "Hello World!";
    $bMsg3[$at3] = 3.14;
    $bMsg3[$at4] = 200.0;

    //As atribuições acima são equivalentes a:
    $bMsg3[0] = 400;
    $bMsg3[""] = "Hello World!";
    $bMsg3[0] = 3.14;
    $bMsg3[0] = 200.0;

Example step by step - ideone


On key/index definition and curious results

The manual describes the behavior of how to define the keys of an array:

  • Keys must be strings or integers only.
  • Strings containing integer values will be converted to integer SINCE valid. The manual suggests the example that "8"(string) will be converted to 8(int) and 08(int) not because it is not a valid decimal. It is not evident that numbers starting with zero are octal, if valid represent another decimal value. If you need to keep zero left on some index number the way to ensure this is to put the value in quotes as a string.

Maybe that’s why programmers confuse Halloween so much with Christmas :).

Ex: 1

$arr = array(031 => 'dezembro');
Saída: 
Array ( [25] => dezembro ) 

Ex: 2

$arr = array('031' => 'dezembro');
Saída:
Array( [031] => dezembro )
  • Floats are converted into integers, this means that only the entire part of the number will be converted into a key.

  • Booleans are converted to integers 0 to false and 1 to true.

  • Nulls are converted to an empty string.

  • Arrays and objects cannot be used as keys, this launched a Warning: Illegal offset type.

  • If multiple elements use the same key, only the last value will be considered the others are overwritten.

Example on items 3 and 7.

$arr = [0.1 => 'a', 0.2 =>'b', 0.3 =>'c'];
echo '<pre>';
print_r($arr);

Exit:

Array
(
    [0] => c
)

Manual - arrays

  • The secret is to "pass" a float as string if it is intended to use the keys thus :)

-1

Best way would be:

$bMsg3 = array(
       $at1 = 0,
       $at2 = "",
       $at3 = 0.0,
       $at4 = 0
);

var_dump($newString=join(" ",$bMsg3));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.