Asked  7 Months ago    Answers:  5   Viewed   30 times

What is the best method for converting a PHP array into a string?
I have the variable $type which is an array of types.

$type = $_POST[type];

I want to store it as a single string in my database with each entry separated by | :

Sports|Festivals|Other

 Answers

15

Use implode

implode("|",$type);
Wednesday, March 31, 2021
 
TheFrack
answered 7 Months ago
77

Use PHP's explode.

$str = "1,2,3,4,5,6";
$arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );

foreach ($arr AS $index => $value)
    $arr[$index] = (int)$value; 

// casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );

As suggested by Tim Cooper, using array_walk is simpler than the above loop:

array_walk($arr, 'intval');
Wednesday, March 31, 2021
 
Magnanimity
answered 7 Months ago
94

To add to Rikesh's answer:

<?php
$aryMain = array(array('hello','bye'), array('',''),array('','')); 
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);

?>

Sticking his code into another array_filter will get rid of the entire arrays themselves.

Array
(
    [0] => Array
        (
            [0] => hello
            [1] => bye
        )

)

Compared to:

$aryMain = array_map('array_filter', $aryMain);

Array
(
    [0] => Array
        (
            [0] => hello
            [1] => bye
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

)
Wednesday, March 31, 2021
 
drowneath
answered 7 Months ago
46

array_diff throws notice errors when it finds an array inside an array. See the comment by Michiel Thalen

I may assume that you're running php 5.4 or higher. You can see it by yourself, by checking your array_diff statement in the sandbox (you can switch php versions there)

There's also a discussion in Drupal forums

As a quickfix I suggest this:

$query = @array_diff($params, array('f' => array()));

And in case you're going to use array_diff function with deep arrays, there are plenty of solutions on the net, including official php.net resource.

Saturday, May 29, 2021
 
Juicy
answered 5 Months ago
66
$dataScope[] = $data;

but

$data[] = $scope;

therefore $dataScope has an array inside it's array. implode only work on one level, so that why you're getting this error.

You should note that this is actually possible in SQL:

 SELECT * FROM some_table WHERE id IN (SELECT site FROM another_table WHERE ... )

which would eliminate the entire need for this code.

That is:

$where = 'WHERE scope_scopes.sc_ID IN (SELECT site
                                       FROM system_scoperights
                                       WHERE user = '. $this->session->userdata('username') . ')';
Saturday, May 29, 2021
 
kensil
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :