Treby
Treby

Reputation: 1320

PHP: Array Segregation

I have this string:

type=openBook&bookid=&guid=7AD92237-D3C7-CD3E-C052-019E1EBC16B8&authorid=&uclass=2&view=

Then I want to get all the values after the "=" sign so for the "type" i want to get "openBook" and put this in an array.

Note: even if it is null it must be added to the array so i wont loose track..

So how can i do that.

Many Thanks

Upvotes: 0

Views: 305

Answers (3)

Ei Maung
Ei Maung

Reputation: 7153

$first = split("&", "type=openBook&bookid=&guid=7AD92237-D3C7-CD3E-C052-019E1EBC16B8&authorid=&uclass=2&view=");

foreach($first as $value) {
    list($key, $val) = split("=", $value);
    $arr[$key] = $val;
}

echo $arr['type'];    // openBook

Upvotes: -1

Boris Guéry
Boris Guéry

Reputation: 47604

You can take a look to explode();

<?php

$foo = "type=openBook&bookid=&guid=7AD92237-D3C7-CD3E-C052-019E1EBC16B8&authorid=&uclass=2&view=";

$chuncks = explode('&', $foo);

$data = array();

foreach ($chuncks as $chunck)
{
  $bar = explode('=', $chunck);
  $data[$bar[0]] = $bar[1];

}

var_dump($data);

Upvotes: 1

Dominic Rodger
Dominic Rodger

Reputation: 99811

I think you want parse_str:

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>

I'm not sure what you mean by this bit:

Note: even if it is null it must be added to the array so i wont loose track..

If parse_str doesn't work quite as you want post a comment and I'll try and help.

Upvotes: 7

Related Questions