break array as a string - php

I have a array:-
Array ( [6] => 1 [6(HL)] => 3 [5] => 1 [7(HL)] => 2 )
How to break it and echo as like this:-
2(6), 3(6(HL)), 1(5), 2(7(HL))
I have try to use implode to break it as a string, but this is what result I get:-
2, 3, 1, 2
any idea on this?
Thanks for advance.

assume your array is $arr :
$output = '';
foreach($arr as $k => $v) {
$output .= $v . '(' . $k . ')' . ', ';
}
$output = substr($output, 0, strlen($output)-2);
echo $output;

$s = implode(', ', array_map(function($a, $b) {
return "$b($a)";
}, array_keys($a), array_values($a)));
Or
$s = '';
foreach ($a as $key => $val)
{
if ($s) $s .= ', ';
$s .= "$val($key)";
}

Related

Extract numbers separated by special char from string

If I have a string like:
123*23*6594*2*-10*12
How can I extract the single numbers, in the string separated by *? That is, I want this output:
a=123, b=23, c=6594, d=2, e=-10, f=12.
Flexible:
$vars = range('a', 'z');
$vals = explode('*', $string);
$result = array_combine(array_slice($vars, 0, count($vals)), $vals);
Result:
Array
(
[a] => 123
[b] => 23
[c] => 6594
[d] => 2
[e] => -10
[f] => 12
)
Just for the sheer fun of setting the result as an iterable (rather than an actual array) with the alpha keys in a slightly different manner:
$data = '123*23*6594*2*-10*12';
function dataseries($data) {
$key = 'a';
while (($x = strpos($data, '*')) !== false) {
yield $key++ => substr($data, 0, $x);
$data = substr($data, ++$x);
}
yield $key++ => $data;
}
foreach(dataseries($data) as $key => $value) {
echo $key, ' = ', $value, PHP_EOL;
}
Requires PHP >= 5.5.0
You can use simple as this :
$str = "123*23*6594*2*-10*12";
$arr = explode("*",$str);
$arr['a']=$arr[0];
$arr['b']=$arr[1];
$arr['c']=$arr[2];
$arr['d']=$arr[3];
$arr['e']=$arr[4];
$arr['f']=$arr[5];
echo "a=" .$arr['a'] ." b=". $arr['b']." c=". $arr['c']." d=". $arr['d']." e=". $arr['e']." f=". $arr['f'];
EDIT:
To accomplish Rizier123 wish :
$str = "123*23*6594*2*-10*12";
$arr = explode("*",$str);
$vars = range('a', 'z');
foreach ($arr as $val => $key){
echo $vars[$val]."=".$key."<br>";
}
something like:
list($a,$b,$c,$d,$e,$f) = explode("*", $str);
Just a guess ;)

PHP: How to print associative array using while loop?

I have a simple associative array.
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
?>
Using only while loop, how can I print it in this result?
$a = 1
$b = 2
$c = 3
This is my current solution but I think that this is not the efficient/best way to do it?
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocArray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocArray[$key] . '<br />';
};
?>
Thanks.
try this syntax and this is best efficient way to do your job...........
while (list($key, $value) = each($array_expression)) {
statement
}
<?php
$data = array('a' => 1, 'b' => 2, 'c' => 3);
print_r($data);
while (list($key, $value) = each($data)) {
echo '$'.$key .'='.$value;
}
?>
For reference please check this link.........
Small Example link here...
The best and easiest way to loop through an array is using foreach
foreach ($assocArray as $key => $value)
echo $key . ' = ' . $value . '<br />';
Try this;
$assocarray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocarray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocarray[$key] . '<br />';
};
I have a simple solution for this, it will get the job done..
$x = array(0=>10,1=>11,2=>"sadsd");
end($x);
$ekey = key($x);
reset($x );
while(true){
echo "<br/>".key($x)." = ".$x[key($x)];
if($ekey == key($x) )break;
next($x);
}
Try code below:
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$obj = new ArrayObject($assocArray);
foreach ( $obj as $key => $value ) {
echo '$' . $key .'='. $value . "<br/>";
}

how to get associative array from string

I have one string like:-
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
Now, I want to get it in following associative array format:-
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
Note:- These all values are separated by space only. Any help will be appreciable.
Thanks in advance
$final_array = array();
$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
list($k, $v) = explode('=', $kvp);
$final_array[$k] = $v;
}
I can suggest you to do it with a regular expression:
$str = "id=1 username=puneet mobile=0987778987 u_id=232";
$matches = array();
preg_match_all( '/(?P<key>\w+)\=(?P<val>[^\s]+)/', $str, $matches );
$res = array_combine( $matches['key'], $matches['val'] );
working example in phpfiddle
$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
$temp2 = explode("=", $v);
$attributes[$temp2[0]] = $temp2[1];
}
EXPLODE
this code will solve your problem.
<?php
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
$a = explode ( ' ', $attributes) ;
$new_array = array();
foreach($a as $value)
{
//echo $value;
$pos = strrpos($value, "=");
$key = substr($value, 0, $pos);
$value = substr($value, $pos+1);
$new_array[$key] = $value;
}
print_r($new_array);
?>
out put of this code is
Array ( [id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232 )
I think you have to split this string two times
divide with space
divide with '='

Getting first 3 values of an array in PHP

Suppose I have an array that looks like this
array ([apple] => 1, [dog]=>2, [cat]=>5, [bread]=>9, [shoes]=> 4)
Is it possible for me to print the first 3 values of the array? If so, how? Any ideas?
$firstThreeElements = array_slice($array, 0, 3);
Where 0 is your offset and 3 is the number of elements you want.
There are many ways.
list( $first, $second, $third) = $array;
echo $first . ' ' . $second . ' ' . $third;
Or:
echo array_shift( $array);
echo array_shift( $array);
echo array_shift( $array);
Or:
$i = 0;
foreach( $array as $el) {
if( $i >= 3) break;
echo $el;
$i++;
}
Or:
foreach( array_slice( $array, 0, 3) as $el) {
echo $el;
}
Or:
echo implode( ' ', array_slice( $array, 0, 3));
Using iterators:
$array = ['apple' => 1, 'dog' => 2, 'cat' => 5, 'bread' => 9, 'shoes' => 4];
foreach (new LimitIterator(new ArrayIterator($array), 0, 3) as $key => $val)
{
echo "$key => $val\n";
}

PHP array manipulation

I have an array as $arr = array("name" => "Fom Xong" , "Sales" => "100");
From this array I want to generate a string something like this
$str = 'name="Fom Xon" Sales="100"';
Is it possible???
thanks in advance
For example you can do like this:
$tmp_arr = array();
foreach ($arr as $key => $val)
$tmp_arr[] = $key.'="'.$val.'"';
$str = implode(' ', $tmp_arr);
$output = array();
foreach ($arr as $key => $value) {
$output[] = "$key=\"$value\"";
}
echo join(' ', $output);
Or:
echo join(' ', array_map(function ($key, $value) { return "$key=\"$value\""; }, array_keys($arr), $arr));

Categories