Take the value of a string within a PHP variable

Asked

Viewed 316 times

1

$a = " A=1 B=2";

I need to use echo in $a and display the value of B. I don’t want to use array. It’s because I’ll create a column in the database where it will house all active options. And I don’t want to go through the trouble of creating more than 10 columns just for options. So it would look like this, the value of the COLUMN opcoes will have option1=true option2=false ...

2 answers

1


You can use parse_str(), but you’d have to do replace from white spaces to &:

<?php
$a = " A=1 B=2";
$a = str_replace(' ','&',$a);
parse_str($a, $valor);
echo $valor['B'];
?>

See on Ideone.

1

The @dvd response works correctly. But there is another approach that can be used with arrays. You can use the function serialize to convert from array to string (and save to database) and unserialize to convert from string to array. The advantage of this is that you can release the use of the comma without having to escape in your options.

An example of this would be:

//dados vindos do formulario
$opcoes = $_POST;

//opções seria algo equivalente 
//a ['opcao1'=>'valor 1', 'opcao 2' => valor2]
$opcoes = serialize($opcoes);//$opcoes agora é uma string

//então salve no banco

//e depois que você ler o campo do banco deserialize assim
$opcoes = $campoLidoDoBanco;//$opcoes é uma string
$opcoes = unserialize($opcoes);//$opcoes agora é um array

Browser other questions tagged

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