1

The following method below works perfectly if $output is a string. Although in a rare case $output can be passed as an array.

How can I check if $output is an array and to only get the last part of the array.

/**
 * Output writer.
 *
 * @param string $output
 * @param Controller $oController
 * @throws Output_Exception
 */
public static function factory($output,Controller $oController) {       

    $outtype =  ucfirst(strtolower(str_replace(".","_",$output)));
    $classname = __CLASS__ . "_" . $outtype;

    try {

        Zend_Loader::loadClass($classname);
        $oOutputter = new $classname($oController);

        if(! $oOutputter instanceof Output_Abstract )
            throw new Output_Exception("class $classname is not an instance of Output_Abstract");

    } catch (Zend_Exception $e) {               
        throw $e;
    }

    return $oOutputter;
}

Errors:

Warning: strtolower() expects parameter 1 to be string, array given in C:\wamp\www\cms\webapp\library\Output.php on line 16

Warning: include_once(Output.php) [function.include-once]: failed to open stream: No such file or directory in C:\wamp\php\includes\Zend\Loader.php on line 146

var_dump($output)

array(2) { [0]=> string(6) "xml" [1]=> string(6) "smarty" } 

3 Answers 3

4
if ( is_array($output) ) {
   $output= end($output);
}

see
http://docs.php.net/is_array
http://docs.php.net/function.end

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

Comments

1

You should be able to use PHP's is_array() function. Something like the following should do it.

<?php
//...
$output = is_array($output) ? $output[count($output)-1] : $output;
//...
?>

This snippet will check if $output is an array, and if it is, it'll set $output to to the last element in the array. Otherwise, it will leave it unchanged.

You can read more about is_array() at the following link:

http://www.php.net/manual/en/function.is-array.php

EDIT: Looks like someone beat me to an answer, but I would recommend against using the end() function here. Doing so could have unexpected results if the code calling your function expects the array to be unmodified.

2 Comments

"Doing so could have unexpected results if the code calling your function expects the array to be unmodified." - Since the array isn't passed as reference that doesn't happen.
Hmm, you're right. For some reason I thought both arrays and objects were passed by reference, but apparently I was wrong about arrays.
0

Try changing this:

$outtype =  ucfirst(strtolower(str_replace(".","_",$output)));

to this:

if(is_array($output))
    $outout= $output[count($outout)-1];
$outtype =  ucfirst(strtolower(str_replace(".","_",$output)));

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.