Norman
Norman

Reputation: 6365

PHP Create an Array or String based on condition

In the following code, I'm trying to create an array or a string based on if type is true or false. If type were true, then i need to create an array else I need to keep things as a string. I was trying as below, but it does not seem to work. Can you help?

<?php
$type = True;

if($type){
    $body = "body['body']"; //Start an array
} else {
    $body = 'body'; //Just a string
}

$body  = 'Hello'; //$body = the value from up there

print_r($body);
?>

Expected Results:

If type = true //Array
print_r($body);
Array ([body] => Hello)

If type = false //String
print_r($body); 
Hello

Edit The content for the array or string is outside the if and comes after it. I need to start as a array or sting based on the type.

Upvotes: 0

Views: 172

Answers (4)

Junaid Atique
Junaid Atique

Reputation: 495

$type  = true;
$value = 'Hello';

if($type){
    $body['body'] = $value;
} else {
    $body = $value;
}
if (is_array($body)) {
// content for array goes here
} else {
// content for string goes here
}
print_r($body);

Upvotes: 0

loler
loler

Reputation: 2587

You can write it on one line with shorthand if.

$body = ($type ? array('body'=>'Hello') : 'Hello');

var_dump($body);

Upvotes: 0

Rohan
Rohan

Reputation: 3332

Try this.

$x = array('body'=>'Hello');
if($type){
    $body = $x;
} else {
    $body = 'body';
}

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

$type  = true;
$value = 'Hello';

if($type){
    $body['body'] = $value;
} else {
    $body = $value;
}

print_r($body);

Upvotes: 3

Related Questions