1

I have an array an add it in foreach loop my code is:

foreach($array as $a) {         
    echo var_dump($a);        
}

and my output is:

enter image description here

how can set my output to this:

enter image description here

and then show count of each value in my array. how can set this?

2
  • 1
    What's wrong with just var_dump($array); ? Commented Mar 5, 2014 at 8:58
  • This comment by Rikesh is the actual answer. Wait till it gets posted as an answer with up votes 10x Commented Mar 5, 2014 at 9:03

3 Answers 3

1

Stony answer is good. But I realize you want to echo the length of the value that you have. So I just expanded Stony's answer.

$myarray = array();

foreach($array as $a) {         
    $myarray[] = $a;
}

foreach($myarray as $key => $value) {         
    echo "Length of $value at index $key is " . strlen($value) . " <br/> ";
}

Note that I use PHP function strlen to calcualate the length of the string. Hope this helps. Thank you.

Sign up to request clarification or add additional context in comments.

Comments

0

Using FOR loop u can do this like

for($i=0;$i<=sizeof($array);$i++)
{
 echo $i."=>".$array[$i]."(length=".sizeof($array[$i]).")";
} 

Comments

0

Try this code,

    $arr = array("value1", "value2", "value3", "value4");
    $newArr = array();
    foreach ($arr as $val) {
        $newArr [] = "string '$val' (length=".strlen($val).")";
    }
    print_r($newArr);exit;

Expected output:

    Array
(
    [0] => string 'value1' (length=6)
    [1] => string 'value2' (length=6)
    [2] => string 'value3' (length=6)
    [3] => string 'value4' (length=6)
)

Try Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.