How to use explode function in PHP? - php

I want to spit my string in to 2 pieces, I know that I have to use explode function in PHP.
Then I want to apply strtolower to my first element, and apply strtoupper for my last element, I just could figure it out where is the pieces are stored after splitting them ?
What I have tried ?
// $value[0] = "8000297C-1360598144";
echo $value[0] . "<br>";
dd(explode('-', $value[0]));
echo "<br>";

The "pieces" are not stored, but returned as the return value:
echo $value[0] . "<br>";
$pieces = explode('-', $value[0]);
echo strtolower($pieces[0]);
echo "<br>";
echo strtoupper($pieces[1]);

$value[0] = "8000297C-1360598144";
$value[0] = explode("-",$value[0]);
$value[0][0] = strtolower($value[0][0]);
$value[0][1] = strtoupper($value[0][1]);
From this, print_r($value); will output
Array
(
[0] => Array
(
[0] => 8000297c
[1] => 1360598144
)
)

// $value[0] = "8000297C-1360598144";
echo $value[0] . "<br>";
$elements = explode('-', $value[0]);
//
$elementzero = isset($elements[0]) ? $elements[0] : null;
$elementone = isset($elements[1]) ? $elements[1] : null;
echo strtolower($elementzero);
echo strtoupper($elementone);
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

You can also do it like this:
$value[0] = "8000297C-1360598144";
list($first, $second) = explode('-', $value[0]);
echo strtolower($first) . PHP_EOL;
echo strtoupper($second) . PHP_EOL;
Best,

Related

is_array function executes strings as well

I'm trying to write a function for arrays that strips the backslashes.
My problem is that I'm using the "is_array" function to verify if the input actually is an array but it seems that it executes numbers and strings as well.
The stripping part seems to work though, so it's the is_array part I can't figure out
I'm using the "array_map" function because the input array could consists of several arrays
What am I missing?
Thanks.
function strip_backslashes_array( $arr )
{
$result = is_array($arr) === true ?
array_map('strip_backslashes_array', $arr) :
implode( "",explode("\\",$arr ));
return $result;
}
$number = 5;
$text = 'Hey th\\\ere!';
$array = array("\\1","2\\",3,4);
$value1 = strip_backslashes_array($number);
echo $value1;
//returns 5. I would expect it to be Null as it is NOT an array.
$value2 = strip_backslashes_array($text);
echo $value2;
//returns "Hey there!" so it has stripped the string but I would expect Null as it is NOT an array.
echo '</br>';
$value3 = sanitize_strip_backslashes_array($array);
print_r($value3);
//returns "Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )" so it has stripped slashes as expected because it is an array.
This function will strip backslashes from array and it will return null in case of other types if you give to the parameter strict true.
<?php
function strip_backslashes_array($arr, $strict = false){
$isarray = is_array($arr);
if ($strict && !$isarray) {
return null;
}
return $isarray? array_map('strip_backslashes_array', $arr) :
implode( "", explode("\\", $arr));
}
$number = 5;
$text = 'Hey th\\\ere!';
$array = array("\\1","2\\",3,4);
echo '</br>';
$value1 = strip_backslashes_array($number, true);
var_dump($value1);
echo '</br>';
$value2 = strip_backslashes_array($text, true);
var_dump($value2);
echo '</br>';
$value3 = strip_backslashes_array($array, true);
var_dump($value3);
Your recursion logic will not work if you want to return null when is_array($arr) == false. You wil need to use a different function to perform the string manipulation.
function strip_backslashes_array( $arr )
{
$result = is_array($arr) ?
array_map('strip_backslashes_str', $arr) :
null;
return $result;
}
function strip_backslashes_str($str){
if (is_array($str))
return strip_backslashes_array($str);
return implode( "", explode("\\", $str));
}

Checking array count and then adding condition to add "and" to last array output

I have successfully create conditions which check the array count. Everything I have is working, but I am trying to figure out how to configure it so that if the results are:
1, 2, 3
I want it to be:
1, 2 and 3
How can I do this?
$proposal_type_arr = $_POST['prop-type'];
$proposal_type_count = count($proposal_type_arr);
if ($proposal_type_count == 1) {
$proposal_type = implode("", $proposal_type_arr);
}
else if ($proposal_type_count == 2) {
$proposal_type = implode(" and ", $proposal_type_arr);
}
else if ($proposal_type_count > 2) {
$proposal_type = implode(", ", $proposal_type_arr);
}
You could use array_pop() to grab the last element in the array. When combined with implode() you'd be able to cut down on the conditional logic.
Example:
$proposal_type_arr = $_POST['prop-type'];
$proposal_type_count = count( $proposal_type_arr );
if ( $proposal_type_count > 1 ) {
$last_el = array_pop( $proposal_type_arr );
$proposal_type = implode( ', ', $proposal_type_arr ) . ' and ' . $last_el;
} else {
$proposal_type = current( $proposal_type_arr );
}
You can do it like this.
Try this code snippet here sample array taken
elseif ($proposal_type_count > 2)
{
$temp=$proposal_type_arr[$proposal_type_count-1];//getting last element
unset($proposal_type_arr[$proposal_type_count-1]);//unsetting last element
$proposal_type = implode(", ", $proposal_type_arr);
echo $proposal_type.= " and $temp";//attaching last element with "and "
}
You can use array_pop to pop the last element out, and if you want to just keep the first two, use array_slice(). Then use implode to trans array to string.
$end = array_pop(&$array);
echo implode(',', $array) . ' and ' . $end;

Implode with default value if no values

I want to show dash(-) if my array is empty after imploding it. Here below is my try so far.
Result with Data in Array -> https://repl.it/HIUy/0
<?php
$array = array(1,2);
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data - ' . implode(',', $result);
//Result : Array With Data : 1,2
?>
Result without Data in Array -> https://repl.it/HIVE/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array Without Data - ' . implode(',', $result);
//Result : Array With Data - :
?>
As you can see in the second result, I am unable to print anything as my array was blank hence I was unable to print anything.
However, I want to print Dash(-) using implode only by using something like array_filter which I already tried but I am unable to do so. Here I have tried this https://repl.it/HIVP/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data : ' . implode(',', array_filter($result));
//Result : Array With Data :
?>
Can someone guide me how to achieve this ?
Thanks
You can check if your array is empty and then return/ echo a Dash:
if(!empty($array)){
// Array contains values, everything ok
echo 'Array with data - ' . implode('yourGlueHere', $array);
} else {
// Array is empty
echo 'Array without data -';
}
If you want to have it in one line, you could do something like the following:
echo 'Array with' . empty($array) == false ? '' : 'out' . 'data - ' . empty($array) == false ? implode('glue', $array) : '';
Answers posted by Tobias F. and Gopi Chand is correct.
Approach 1:
I'd suggest you going this way would help you (Basically using ternary operator).
As here is no other way of doing this using just implode function.
echo empty($result) ? '-' : implode(',',$result);
Approach 2
Using a helper function like this.
function myImpllode($glue = "", $array = [])
{
if(!empty($array)){
// Array contains values, everything ok
return implode($glue, $array);
} else {
// Array is empty
return '-';
}
}

Why do I get "Undefined variable" when trying to resolve a multi-dimensional array?

I'm trying to retrieve an item from a multi-dimensional array through a string that describes the path into the array (like first.second.third).
I've chosen the approach as shown here (also available on ideone):
<?php
// The path into the array
$GET_VARIABLE = "a.b.c";
// Some example data
$GLOBALS["a"]= array("b"=>array("c"=>"foo"));
// Construct an accessor into the array
$variablePath = explode( ".", $GET_VARIABLE );
$accessor = implode( "' ][ '", $variablePath );
$variable = "\$GLOBALS[ '". $accessor . "' ]";
// Print the value for debugging purposes (this works fine)
echo $GLOBALS["a"]["b"]["c"] . "\n";
// Try to evaluate the accessor (this will fail)
echo $$variable;
?>
When I run the script, it will print two lines:
foo
PHP Notice: Undefined variable: $GLOBALS[ 'a' ][ 'b' ][ 'c' ] in ...
So, why does this not evaluate properly?
I think the $$ notation only accepts a variable name (ie. the name of a variable). You are actually trying to read a variable named "$GLOBALS[ 'a' ][ 'b' ][ 'c' ]", which does not exist.
As an alternative ($GET_VARIABLE seems to be your input string), you could try this:
$path = explode('.', $GET_VARIABLE);
echo $GLOBALS[$path[0]][$path[1]][path[2]];
Wrap this in a suitable loop to make it more dynamic; it seems to be trivial.
It looks like PHP is treating your entire string like a variable name, and not as an array.
You could try using the following approach instead, as it would also probably be simpler.
<?php
// The path into the array
$GET_VARIABLE = "a.b.c";
// Some example data
$GLOBALS["a"]= array("b"=>array("c"=>"foo"));
// Construct an accessor into the array
$variablePath = explode( ".", $GET_VARIABLE );
//$accessor = implode( "' ][ '", $variablePath );
//$variable = "\$GLOBALS[ '". $accessor . "' ]";
// Print the value for debugging purposes (this works fine)
echo $GLOBALS["a"]["b"]["c"] . "\n";
// Try to evaluate the accessor (this will fail)
echo $GLOBALS[$variablePath[0]][$variablePath[1]][$variablePath[2]];
?>
Here's some code I wrote to access $_SESSION variables via dot notation. You should be able to translate it fairly easily.
<?php
$key = "a.b.c";
$key_bits = explode(".", $key);
$cursor = $_SESSION;
foreach ($key_bits as $bit)
{
if (isset($cursor[$bit]))
{
$cursor = $cursor[$bit];
}
else
{
return false;
}
}
return $cursor;
Here's one more solution using a helper function:
function GetValue($path, $scope = false){
$result = !empty($scope) ? $scope : $GLOBALS;
// make notation uniform
$path = preg_replace('/\[([^\]]+)\]/', '.$1', $path); // arrays
$path = str_replace('->', '.', $path); // object properties
foreach (explode('.', $path) as $part){
if (is_array($result) && array_key_exists($part, $result)){
$result = $result[$part];
} else if (is_object($result) && property_exists($result, $part)){
$result = $result->$part;
} else {
return false; // erroneous
}
}
return $result;
}
And example usage:
// Some example data
$GLOBALS["a"] = array(
'b' => array(
'c' => 'foo',
'd' => 'bar',
),
'e' => (object)array(
'f' => 'foo',
'g' => 'bar'
)
);
$bar = array(
'a' => $GLOBALS['a']
);
echo $GLOBALS['a']['b']['c'] . "\n"; // original
// $GLOBALS['a']['b']['c']
echo GetValue('a.b.c') . "\n"; // traditional usage
// $GLOBALS['a']['b']['c']
echo GetValue('a[b][c]') . "\n"; // different notation
// $bar['a']['b']['c']
echo GetValue('a.b.c', $bar) . "\n"; // changing root object
// $GLOBALS['a']['e']->f
echo GetValue('a[e]->f') . "\n"; // object notation

How can I display an array in a human readable format?

If I have an array that looks like this:
$str = '';
if( $_POST['first'] )
$str = $_POST['first'];
if( $_POST['second'] )
$str .= ($str != '' ? ',' : '') . $_POST['second'];
if( $_POST['third'] )
$str .= ($str != '' ? ',' : '') . $_POST['third'];
if( $_POST['fourth'] )
$str .= ($str != '' ? ',' : '') . $_POST['second'];
$str .= ($str != '' ? '.' : '');
Which gives me something like this:
Joe, Adam, Mike.
However, I would like to add an "and" before the last item.
So it would then read:
Joe, Adam, and Mike.
How can I modify my code to do this?
Arrays are awesome for this:
$str = array();
foreach (array('first','second','third','fourth') as $k) {
if (isset($_POST[$k]) && $_POST[$k]) {
$str[] = $_POST[$k];
}
}
$last = array_pop($str);
echo implode(", ", $str) . " and " . $last;
You should probably special case the above for when there's one item. I, in fact, wrote a function called "conjunction" which does the above, and includes the special case:
function conjunction($x, $c="or")
{
if (count($x) <= 1) {
return implode("", $x);
}
$ll = array_pop($x);
return implode(", ", $x) . " $c $ll";
}
Nice question!
Updated: General purpose way to do this:
function and_form_fields($fields)
{
$str = array();
foreach ($fields as $k) {
if (array_key_exists($k, $_POST) && $v = trim($_POST[$k])) {
$str[] = $v;
}
}
return conjunction($str, "and");
}
...
and_form_fields(array("Name_1","Name_2",...));
I added correct $_POST checking to avoid notices, and blank values.
The first ideea that comes to my mind is to always keep a last one name in an auxiliar variabile. When you have another one to put in, you take it put the 'comma' and get the next name in the aux.
At the end, when you finished added the names, you add 'and' and the last name from aux.
Instead of posting each as a separate variable, why not post them as an array:
#pull the array from the POST:
$postedarray = $_POST['names'];
#count the number of elements in the posted array:
$numinarray = count($postedarray);
#subtract 1 from the number of elements, because array elements start at 0
$numinarray = $numinarray -1;
#set a prepend string
$prependstr = "and ";
#Pull the last element of the array
$lastname = $postedarray[$numinarray];
#re-define the last element to contan the prepended string
$postedarray[$numinarray] = "$prependstr$lastname";
#format the array for your requested output
$comma_separated = implode(", ", $postedarray);
print "$comma_separated";

Categories