Jump to content

Array help


Canman2005

Recommended Posts

Hi all

 

I have an array set under

 

$_SESSION['items']

 

so if I do a

 

print_r($_SESSION['items']);

 

then I get

 

( [1] => 4 [45] => 2 )

 

what I want to do is implode that array so that I get an output that looks like

 

1,45

 

but I cannot figure it out.

 

If I use

 

print implode(",", $_SESSION['items']);

 

then that outputs

 

4,2

 

but I want it to output

 

1,45

 

instead

 

any ideas?

 

thanks

 

ed

Link to comment
Share on other sites

Try...

 

$output_string = '';
$start = TRUE;
foreach ($_SESSION['items'] as $key => $value) {
    if (!$start) 
        $output_string .= ', ';
    else
       $start = FALSE;
    $output_string .= $key;
}

// Do whatever you want with $output_string

Link to comment
Share on other sites

coooool, thanks for that everyone

 

I wonder if you could help me further

 

Is it possible to pull a single value from an array?

 

Let me explain.

 

My array currently looks like

 

( [1] => 4 [45] => 2 )

 

so with the above

 

45 is linked to 2  ([45] => 2)

 

and

 

1 is liked to 4  ([1] => 4)

 

so is it possible for example, to supply var such as

 

$var = 45

 

and run something so that it grabs the value

 

2

 

or if I supplied

 

$var = 1

 

then it would allow me to grab value

 

4

 

any help would be fab

 

thanks all

Link to comment
Share on other sites

yes, just use the square bracket operator to supply whatever index you want

$key = 45
echo $_SESSION['item'][$key];//echos 2

//store the 2 from $_SESSION['item'] in a variable
$two = $_SESSION['item'][$key];

//alternatively, this will also work
$two = $_SESSION['item'][45];

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.