I'am executing code :
<?php
$input="ABC123";
$splits = chunk_split($input,2,"");
foreach($splits as $split)
{
$split = strrev($split);
$input = $input . $split;
}
?>
And output that i want is :
BA1C32
But it gaves me Warning.
Warning: Invalid argument supplied for foreach() in /home/WOOOOOOOOHOOOOOOOO/domains/badhamburgers.com/public_html/index.php on line 4
chunk_split doesn't return an array but rather a part of the string.
You should use str_split instead:
$input="ABC123";
$splits = str_split($input, 2);
And don't forget to reset your $input before the loop, else it will contain the old data aswell.
It looks like http://php.net/manual/en/function.chunk-split.php returns a string, not an array. You could use str_split instead:
$input = "ABC123";
$splits = str_split( $input, 2 );
$output = "";
foreach( $splits as $split ){
$split = strrev($split);
$output .= $split;
}
As the documentation for chunk_split mentions clearly, http://php.net/manual/en/function.chunk-split.php chunk split returns a string.
foreach expects an array as first argument.
Related
This question already has answers here:
Explode a string to associative array without using loops? [duplicate]
(10 answers)
Closed 7 months ago.
I have a PHP string separated by characters like this :
$str = "var1,'Hello'|var2,'World'|";
I use explode function and split my string in array like this :
$sub_str = explode("|", $str);
and it returns:
$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";
Is there any way to explode $substr in array with this condition:
first part of $substr is array index and second part of $substr is variable?
example :
$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';
and when I called my $new_substr it return just result ?
example :
echo $new_substr["var1"];
and return : hello
try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
$data = explode(',', $string);
if(isset($data[0]) && !empty($data[0])){
$array[$data[0]] = $data[1];
}
}
You can do this using preg_match_all to extract the keys and values, then using array_combine to put them together:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
Output:
Array (
[var1] => 'Hello'
[var2] => 'World'
)
Demo on 3v4l.org
You can do it with explode(), str_replace() functions.
The Steps are simple:
1) Split the string into two segments with |, this will form an array with two elements.
2) Loop over the splitted array.
3) Replace single quotes as not required.
4) Replace the foreach current element with comma (,)
5) Now, we have keys and values separated.
6) Append it to an array.
7) Enjoy!!!
Code:
<?php
$string = "var1,'Hello'|var2,'World'|";
$finalArray = array();
$asArr = explode('|', $string );
$find = ["'",];
$replace = [''];
foreach( $asArr as $val ){
$val = str_replace($find, $replace, $val);
$tmp = explode( ',', $val );
if (! empty($tmp[0]) && ! empty($tmp[1])) {
$finalArray[ $tmp[0] ] = $tmp[1];
}
}
echo '<pre>';print_r($finalArray);echo '</pre>';
Output:
Array
(
[var1] => Hello
[var2] => World
)
See it live:
Try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
$test_str = explode( ',', $row );
if ( 2 == count( $test_str ) ) {
$new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
}
}
print $new_str['var1'] . ' ' . $new_str['var2'];
Just exploding your $sub_str with the comma in a loop and replacing single quote from the value to provide the expected result.
This is my code:
function get_random(){
$filter_word = '1,2,3,4,5,6,7,8,9';
$array = explode(',', $filter_word);
$randomKeys = array_rand($array, 2);
$str = '';
foreach($randomKeys as $key){
$str = $array[$key];
}
return $str;
}
The problem that if I used array_rand i must know the number of elements to can add the number in array_rand and I can't know something like this (it's a data stored into the database) so if the elements are less than two it gives me an error:
Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array
Is there a better way to make this?
you can use count() before using array_rand-
function get_random(){
$filter_word = '1,2,3,4,5,6,7,8,9';
$array = explode(',', $filter_word);
$str = '';
if(count($array)>1){
$randomKeys = array_rand($array, 2);
foreach($randomKeys as $key){
$str = $array[$key];
}
}
else{
$str = $filter_word;
}
return $str;
}
I suppose you are looking for something like this:
$randCount = rand(1, count($array));
$randomKeys = array_rand($array, $randCount);
Trying to use the implode() function to add a string at the end of each element.
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array);
print($attUsers);
Prints this:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132
How do I get implode() to also append the glue for the last element?
Expected output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
//^^^^^^^^^^^^ See here
There is a simpler, better, more efficient way to achieve this using array_map and a lambda function:
$numbers = ['9898549130', '9898549131', '9898549132'];
$attUsers = implode(
',',
array_map(
function($number) {
return($number . '#txt.att.net');
},
$numbers
)
);
print_r($attUsers);
This seems to work, not sure its the best way to do it:
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array) . "#txt.att.net";
print($attUsers);
Append an empty string to your array before imploding.
But then we have another problem, a trailing comma at the end.
So, remove it.
Input:
$array = array('9898549130', '9898549131', '9898549132', '');
$attUsers = implode("#txt.att.net,", $array);
$attUsers = rtrim($attUsers, ",")
Output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
This was an answer from my friend that seemed to provide the simplest solution using a foreach.
$array = array ('1112223333', '4445556666', '7778889999');
// Loop over array and add "#att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
$array[$index] = $phone_number . '#att.com';
}
// join array with a comma
$attusers = implode(',',$array);
print($attusers);
$result = '';
foreach($array as $a) {
$result = $result . $a . '#txt.att.net,';
}
$result = trim($result,',');
There is a simple solution to achieve this :
$i = 1;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ == $c) {
$array[$key] .= '#txt.att.net';
}
}
I'm retrieving this value from single block of the table i.e,
sample1,sample2,sample3,
I dont want the last comma to be retrieved as my output is creating an empty result at the end. Here's my code:
$imageExtractExplode = explode(",", $imageExtract);
foreach
($imageExtractExplode as $imageExtractFinal){
//my echo code
}
How do i stop the last comma from getting displayed
Can you try this, You can use rtrim function to remove last comma and explode the removed string.
$imageExtract = rtrim("sample1,sample2,sample3,", ",");
$imageExtractExplode = explode(",", $imageExtract);
foreach($imageExtractExplode as $imageExtractFinal){
//my echo code
}
OR substr($string, 0, -1);
$imageExtract = substr("sample1,sample2,sample3,", 0, -1);
$imageExtractExplode = explode(",", $imageExtract);
foreach($imageExtractExplode as $imageExtractFinal){
//my echo code
}
You could use preg_split() instead of explode() as it gives you a way to ignore empty strings:
$imageExtractExplode = preg_split("/,/", $imageExtract, -1, PREG_SPLIT_NO_EMPTY);
That way you also avoid empty string problems if there are two commas in a row.
See details here: http://us1.php.net/manual/en/function.preg-split.php
$imageExtractExplode = explode(",", $imageExtract);
array_pop($imageExtractExplode); // THIS .. !
foreach($imageExtractExplode as $imageExtractFinal){
//my echo code
}
$imageExtract = rtrim($imageExtract,',');
$imageExtractExplode = explode(",", $imageExtract);
foreach ($imageExtractExplode as $imageExtractFinal){
//my echo code
}
Are you using an earlier version of PHP? I don't seem to have that problem but I'm running 5.3.
// Explode the values
$imageExtractExplode = explode(",", $imageExtract);
// Run foreach loop
foreach ($imageExtractExplode as $imageExtractFinal) {
// Check to see if the value is empty or not. If it is empty, skip it.
if (!empty($imageExtractFinal)) {
//my echo code
}
}
You can use substr to extract part of the string.
$str = "sample1,sample2,sample3,";
$rs = substr($str, 0, -1); // returns "sample1,sample2,sample3"
I prefer using reset and end to generate a custom last() function - see this answer from Rok Kralj for details.
function last($array, $key) {
end($array);
return $key === key($array);
}
foreach($array as $key => $element) {
if (last($array, $key))
echo 'LAST ELEMENT!';
}
My string is like the following format:
$string =
"name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
I want to split the string like the following:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
how can I do this in PHP ?
Try this:
$matches = array();
preg_match_all("/(name=[a-zA-Z0-9%_-]+&id=[0-9]+)/",$string,$matches);
$matches is now an array with the strings you wanted.
Update
function get_keys_and_values($string /* i.e. name=yyy&id=10 */) {
$return = array();
$key_values = split("&",$string);
foreach ($key_values as $key_value) {
$kv_split = split("=",$key_value);
$return[$kv_split[0]] = urldecode($kv_split[1]);
}
return $return;
}
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
$arr = split("name=", $string);
$strings = aray();
for($i = 1; $i < count($arr), $i++){
$strings[$i-1] = "name=".substr($arr[$i],0,-1);
}
The results will be in $strings
I will suggest using much simpler term
Here is an example
$string = "name=xxx&id=11;name=yyy&id=12;name=zzz&id=13;name=aaa&id=10";
$arr = explode(";",$string); //here is your array
If you want to do what you asked, nothing more or less , that's explode('&', $string).
If you have botched up your example and you have a HTTP query string then you want to look at parse_str().